首页 > 解决方案 > 如何使用 position: absolute 定位元素,使其下半部分隐藏在视口下方?底部:-50%;不工作

问题描述

正如您在下面的片段中看到的,我在页面底部有一个绝对定位的红色圆圈。我想要实现的是让圆的上半部分在屏幕的底部可见,而将下半部分隐藏在视口的底线下方。

我想做底部:-50% 会解决我的问题,但是,它隐藏了超过 70-80% 的圆圈,这让我感到困惑。

    *, *:after, *:before {
        margin: 0;
        padding: 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    }
    body {
        background-color: #000;
        color: white;
    }
        .container {
        position: relative;
        height: 100vh;
        width: 100vw;
        display: flex;
        justify-content: center;
        overflow: hidden;
    }
        .test-layer8 {
        position: absolute;
        background-color: red;
        border-radius: 50%;
        bottom: -50%;
        width: 500px;
        height: 500px;
    }
<div class="container" @mousemove='getCoordinates($event)'>
    <div class="test-layer8"></div>
</div>

标签: htmlcss

解决方案


使用绝对位置,一旦元素被发送到坐标,边距或平移可以帮助重置屏幕上的位置:

  • bottom:0;+translateY(50%)可能会在这里帮助你

*, *:after, *:before {
        margin: 0;
        padding: 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    }
    body {
        background-color: #000;
        color: white;
    }
        .container {
        position: relative;
        height: 100vh;
        width: 100vw;
        display: flex;
        justify-content: center;
        overflow: hidden;
    }
        .test-layer8 {
        position: absolute;
        background-color: red;
        border-radius: 50%;
        bottom: 0;
        transform:translateY(50%);
        width: 500px;
        height: 500px;
    }
<div class="container" @mousemove='getCoordinates($event)'>
    <div class="test-layer8"></div>
</div>

  • 从已知高度 : bottom : 0 ;+ margin-bottom -x; 也可以。

*, *:after, *:before {
        margin: 0;
        padding: 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    }
    body {
        background-color: #000;
        color: white;
    }
        .container {
        position: relative;
        height: 100vh;
        width: 100vw;
        display: flex;
        justify-content: center;
        overflow: hidden;
    }
        .test-layer8 {
        position: absolute;
        background-color: red;
        border-radius: 50%;
        bottom: 0;
        margin-bottom:-250px;
        width: 500px;
        height: 500px;
    }
<div class="container" @mousemove='getCoordinates($event)'>
    <div class="test-layer8"></div>
</div>


推荐阅读