通过位置显示参考底图:坚持滚动的绝对值

时间:2017-12-10 13:18:19

标签: css css-position absolute

我在CSS中使用position:absolute来为下一个div创建一个底层但是一旦我开始滚动,底衬就会保持原位,只有下一个div会移动。我想让底层移动与他们的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>

1 个答案:

答案 0 :(得分:2)

只需将position:relative添加到内部以使其相对于内部的位置:

.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>