我正在尝试创建一个可滚动的 div,其中包含绝对定位的子元素。我希望绝对定位的元素即使在滚动父元素时也可见。我知道我需要将父元素设置为 position: relative 才能实现此目的,但我使用的是 Bootstrap 4,如果我将父元素设置为 relative,则没有任何变化。
Here you can see the starting state, when the parent is scrollable. 注意 lines-scrollable 类:
<div id="opened" class="col-12 align-self-start lines lines-scrollable">
Here you can see the state when the overlay and the popup (absolute positioned children) are displayed.请注意其父级的 lines-non-scrollable 类:
<div id="opened" class="col-12 align-self-start lines lines-non-scrollable">
此时一切正常,因为滚动位置为 0:
$('#opened').scrollTop(0);
$('#opened').scrollTop(100);
最佳答案
当你将某物设置为绝对时,你将它放在相对于容器的位置(最近的容器具有绝对或相对位置......)。但是,当您向下滚动时,0 位置会上升,这就是您看到此行为的原因。
换句话说,当您向上滚动 div 时,相对位置 0 也会发生变化,因此内部绝对 div 也会向上滚动。
你有两个选择:
- List item 将位置设置为固定的,但是这使得它相对于页面(如此固定位置 top: 0;无论它在 html 中的什么位置,它总是在页面的顶部
或
- 将内部绝对 div 向上移动一层并使容器相对,这样您的 HTML 将如下所示:
https://jsfiddle.net/3adctabu/6/ - 您为第二次选择提供的 jsfiddle 的工作示例。
<div class="outer-container-that-is-relative">
<div class="inner-absolute"></div>
<div class="scrollable-content"></div>
</div>
关于html - Bootstrap 4 中可滚动 div 内的 CSS 绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50198660/