无法理解为什么绝对定位的元素在滚动时没有停留在预期位置?

问题描述 投票:0回答:1

为什么当父元素类

child1
(相对位置,溢出滚动)滚动时,类
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>
html css css-position overflow
1个回答
0
投票

你的问题很混乱,所以如果我的回答不能让你满意,请澄清一下。

在你的css child1中没有position:absolute,但是在你写的描述中

child1(绝对位置)

所以场景:

  1. child1 没有绝对位置

那么显然它会随着滚动而移动

  1. child1 具有绝对位置

然后它对于最近的相对元素是绝对的,因此向下滚动时它会向上移动(与您提供的代码中的 child2 相同)

这是一个 child1 在滚动时保持原位的示例

<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;
    position: absolute;
}
.child2{
    height:200%; /* changed to create overflow to be able to scroll */
    width:100%;
    top:0;
    left:0;
    background:rgba(0,0,0,0.5);
}
</style>
<div id="overflowTest">
    <div class="child1"></div>
    <div class="child2"></div>
</div>

我添加了相对于 body 的位置:并将其从 #overflowTest 和 .child2 中删除,以创建能够滚动的溢出。

© www.soinside.com 2019 - 2024. All rights reserved.