绝对定位的div在绝对定位的父元素内滚动

3

我有一个绝对定位的div,里面有两个子元素-- 一个绝对定位的div和一个静态的div,后者将在父元素内滚动。它看起来像这样:

<div class='frame'>
  <div class='absolute-contents'>This should stay put.</div>
  <div class='static-contents'>This should scroll under it.</div>
</div>

以下是CSS代码:

.frame {
  position: absolute;
  top: 40px;
  left: 40px;
  right: 40px;
  bottom: 40px;
  overflow-y: scroll;
}

.absolute-contents {
  position: absolute;
  top: 40px;
  left: 40px;
  right: 40px;
  bottom: 40px;
  z-index: 9999;
  opacity: .9;
  padding: 40px;
}

.static-contents {
  margin: 24px auto;
  width: 400px;
  height: 3000px;
  padding: 40px;
}

我将子元素绝对约束到父元素的边缘,但为什么它仍然可以滚动,我该如何使其保持不变?
示例: https://codepen.io/anon/pen/wqZxXG

你尝试过使用 position: fixed; 吗? - A. W.
是的。但我希望它在父级内固定,而不是整个窗口。 - Dustin Locke
2个回答

8

我通过将想要滚动的元素放在一个绝对定位的

内,并使用overflow-y: scroll属性进行解决,如下所示:

<div class='frame'>
  <div class='fix-me'></div>
  <div class='scroll-me'>
    <div class='long-content'></div>
  </div>
</div>

并且样式像这样:

.frame {
  background-color: blue;
  position: absolute;
  top: 40px;
  right: 40px;
  left: 40px;
  bottom: 40px;
  overflow-y: hidden;
}

.scroll-me {
  background-color: orange;
  position: absolute;
  top: 40px;
  right: 40px;
  left: 40px;
  bottom: 40px;
  overflow-y: scroll;
}

.fix-me {
  position: absolute;
  z-index: 999;
  top: 40px;
  left: 40px;
  right: 40px;
  height: 56px;
  background-color: purple;
}

.long-content {
  width: 480px;
  background-color: yellow;
  height: 4000px;
  margin: 20px auto;
}

在这里可以找到代码: https://codepen.io/dustinlocke/pen/vJMzpK


看起来你已经通过额外的标记解决了问题,这与我回答中链接的问题类似。干得好! - TylerH

5
如果你不想使子div移动,你需要将其调整为使用position: fixed。而position: absolute只是告诉div该元素的初始位置应当绝对定位。在此处查看我的回答here更多关于position: fixed以及类似情况的信息。
.frame div设置为position: relative(或者.frame的父元素)来实现这个功能。这将使得position: fixed的子元素固定在.frameposition: relative父元素内。
你需要调整不同堆叠上下文的位置数值(top, bottom, left, right)。
类似这样: https://codepen.io/anon/pen/brJxVW

body {
  width: 100vw;
}

.frame {
  background-color: green;
  position: relative;
  width: calc(100vw - 80px);
  margin: 0 auto;
  top: 40px;
  bottom: 40px;
  overflow-y: scroll;
}

.absolute-contents {
  background-color: yellow;
  position: fixed;
  top: 40px;
  left: 40px;
  right: 40px;
  bottom: 40px;
  z-index: 9999;
  opacity: .9;
  margin: 40px;
}

.big-contents {
  margin: 24px auto;
  width: 400px;
  height: 3000px;
  background-color: white;
  padding: 40px;
}
<div class='frame'>
    <div class='absolute-contents'>This should stay fixed in the green frame. Why is it scrolling?</div>
    <div class='big-contents'>This should scroll under it.</div>
</div>


你的笔固定了整个窗口内的子div,而不仅仅是“.frame”元素,并滚动整个页面。我想只滚动绿色“.frame”内的元素,并在该绿色“.frame”中固定“.absolute-content”。 - Dustin Locke
从你的演示中可以看出,.frame 是文档中唯一的东西。我晚点回家后会更新,为了更好地帮助我,我会添加一些环境真实的元素到你的演示中。 - TylerH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接