通过 position:absolute 显示支持滚动的底层
Displaying an underlay via position:absolute that adheres to scrolling
我在 CSS 中使用 position:absolute 来为下一个 div 创建一个底层,但是一旦我开始滚动,底层就会保持原位,只有下一个 divs 会移动。我想让底衬随着 div 一起移动,但我不确定如何在 CSS 中做到这一点。
示例代码:
.inner {
height: 2em;
width: 300px;
overflow-y: scroll;
}
.progress {
position: absolute;
width: 20px;
background-color: green;
opacity: 0.4;
height: 20px;
}
<div class='inner'>
<div class='progress'></div>
<div>hello</div>
<div>hello2</div>
<div class='progress'></div>
<div>hello3</div>
</div>
只需将 position:relative
添加到 inner 使其相对于 inner 的位置:
.inner {
height: 2em;
width: 300px;
overflow-y: scroll;
position:relative;
}
.progress {
position: absolute;
width: 20px;
background-color: green;
opacity: 0.4;
height: 20px;
}
<div class='inner'>
<div class='progress'></div>
<div>hello</div>
<div>hello2</div>
<div class='progress'></div>
<div>hello3</div>
</div>
如果您对其他解决方案感兴趣,可以使用伪元素来避免添加额外的元素:
.inner {
height: 2em;
width: 300px;
overflow-y: scroll;
}
.progress {
position: relative;
}
.progress:after {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 20px;
background-color: green;
opacity: 0.4;
}
<div class='inner'>
<div class='progress'>hello</div>
<div>hello2</div>
<div class='progress'>hello3</div>
</div>
我在 CSS 中使用 position:absolute 来为下一个 div 创建一个底层,但是一旦我开始滚动,底层就会保持原位,只有下一个 divs 会移动。我想让底衬随着 div 一起移动,但我不确定如何在 CSS 中做到这一点。
示例代码:
.inner {
height: 2em;
width: 300px;
overflow-y: scroll;
}
.progress {
position: absolute;
width: 20px;
background-color: green;
opacity: 0.4;
height: 20px;
}
<div class='inner'>
<div class='progress'></div>
<div>hello</div>
<div>hello2</div>
<div class='progress'></div>
<div>hello3</div>
</div>
只需将 position:relative
添加到 inner 使其相对于 inner 的位置:
.inner {
height: 2em;
width: 300px;
overflow-y: scroll;
position:relative;
}
.progress {
position: absolute;
width: 20px;
background-color: green;
opacity: 0.4;
height: 20px;
}
<div class='inner'>
<div class='progress'></div>
<div>hello</div>
<div>hello2</div>
<div class='progress'></div>
<div>hello3</div>
</div>
如果您对其他解决方案感兴趣,可以使用伪元素来避免添加额外的元素:
.inner {
height: 2em;
width: 300px;
overflow-y: scroll;
}
.progress {
position: relative;
}
.progress:after {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 20px;
background-color: green;
opacity: 0.4;
}
<div class='inner'>
<div class='progress'>hello</div>
<div>hello2</div>
<div class='progress'>hello3</div>
</div>