提问人:sql_dummy 提问时间:10/28/2023 最后编辑:sql_dummy 更新时间:10/30/2023 访问量:35
无法理解为什么绝对定位的元素在滚动时没有停留在预期位置?
Unable to understand why the absolute positioned element doesnt stay at the intended position when scrolled?
问:
为什么当滚动父元素类(位置相对,溢出滚动)时,具有类(绝对位置)的元素不会停留在预期位置。child2
overflowTest
当我滚动时,我假设父元素(高度、宽度、位置)没有任何变化,因此对子元素类没有影响,只有子元素类移动。但我真正注意到的是,我也被感动了。我无法正确理解/想象正在发生的事情,child2
child1
child2
-- * css *--
#overflowTest {
color: white;
padding: 15px;
height:70%;
width: 50%;
height: 100px;
overflow: scroll;
border: 1px solid #ccc;
position:relative;
background:green;
}
.child1{
height:800px;
width:10px;
background:red
}
.child2{
height:100%;
width:100%;
position:absolute;
top:0;
left:0;
background:rgba(0,0,0,0.5)
}
-- * HTML * --
<div id="overflowTest">
<div class="child1"></div>
<div class="child2"></div>
</div>
答:
0赞
Unlucky
10/28/2023
#1
child2
定位为绝对值,但相对于最近的祖先,所以当你滚动容器(这里)时,也会被滚动,因为“它与容器有关系()”。position: relative
#overflowTest
child2
relative
如果从 移动到 ,则滚动不会影响,因为它与 body 元素相关(因此滚动 body 会影响 )。position: relative
#overflowTest
body
#overflowTest
child2
child2
代码如下
<style>
body {
position: relative;
}
#overflowTest {
color: white;
padding: 15px;
height:70%;
width: 50%;
height: 100px;
overflow: scroll;
border: 1px solid #ccc;
background:green;
}
.child1{
height:800px;
width:10px;
background:red
}
.child2{
height:10%;
width:10%;
position:absolute;
top:0;
left:0;
background:rgba(0,0,0,0.5)
}
</style>
<div id="overflowTest">
<div class="child1"></div>
<div class="child2"></div>
</div>
您还可以使用:position: fixed
位置为:固定的元素;相对于视口定位,这意味着即使页面滚动,它也始终保持在同一位置
~ W3学校
有时很有用position: sticky
我建议访问 W3Schools 链接,那里解释得很好,如果您有任何其他问题,请随时在评论中提问
评论
0赞
sql_dummy
10/30/2023
对不起,我现在已经纠正了
0赞
Unlucky
10/30/2023
@sql_dummy我已经更新了我的答案,希望它现在有所帮助
评论