不扩展父对象的绝对定位



我正试图在一个包含其他元素的div元素中定位一个"seeker"。我希望seeker能够在内容div的顶部移动,而不需要推送其他内容,同时也可以跟随滚动条。该区域可调整大小,因此我不能使用恒定的宽度/高度。就像视频编辑器中的探索者一样。

这就是我到目前为止得到的

#container {
width: 200px;
height:100px;
background-color: gray;
overflow: scroll;
}
#content {
width: 300px;
height: 120px;
}
#box {
width: 40px;
height: 40px;
background-color: green;
}
#seekerContainer {
position: relative;
width: 100%;
height: 100%;
}
#seeker {
width: 4px;
height: 100%;
position: relative;
background-color: blue;
left: 10%;
}
<div id="container">
<div id="content">
<div id="seekerContainer">
<div id="seeker"></div>
</div>

<div id="box"></div>
</div>
</div>

我已经尝试了不同的组合,使seekerContainer和seeker是位置绝对/相对的,但要么seeker不会跟随滚动,要么它扩展了div的高度。

有什么建议可以解决这个问题吗?

我想这就是您想要的:

.container {
width: 200px;
height: 100px;
background-color: gray;
overflow: scroll;
}
.content {
height: 500px;
position: relative;
}
.box {
width: 40px;
height: 40px;
background-color: green;
}
.seeker {
width: 4px;
height: 100%;
position: absolute;
background-color: blue;
left: 10%;
top: 0;
}
<div class="container">
<div class="content">
<div class="seeker"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>

此外,您不希望在每个元素上都放置id,并使用id进行样式设置。为此,您应该使用classes。元素的ID对于页面来说必须是唯一的,所以当您需要将相同的样式应用于更多元素时,它并不是很有用。

最新更新