绝对定位的div在绝对定位的父级内滚动

时间:2017-09-05 20:33:29

标签: html css css3

我有一个绝对定位的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

2 个答案:

答案 0 :(得分:5)

如果您不想移动,请调整您的子div以使用position: fixedposition: absolute只是告诉div它应该绝对确定其初始位置。有关position: fixed的更多信息以及与您类似的方案,请参阅我的回答here

.frame div设置为position: relative(或.frame的父级)以使其生效。这会将position: fixed子项设置为position: relative的{​​{1}}父项。

您需要调整定位金额(顶部,底部,左侧,右侧)以考虑不同的堆叠上下文。

像这样:https://codepen.io/anon/pen/brJxVW

.frame
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;
}

答案 1 :(得分:3)

我决定将我想要的元素放在一个绝对定位的div中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