在 div 容器内的固定位置元素

6

我在一个容器中有一个固定的块元素。滚动时,固定定位的元素超出了容器范围。我知道固定元素将根据窗口vw定位。但是否有办法确保固定定位的元素只滚动到容器位置。固定定位的元素不应超出容器。

问题可以在以下内容中看到。

https://codepen.io/anon/pen/dKLByX

我尝试使用以下方法解决问题:

if($(window).scrollTop()>1900){
    $('.fixed-ct').css({'bottom':'200px','top':'auto'});
}else if($(document).scrollTop() <=100) {
    $('.fixed-ct').css({'top':'10px','bottom':'auto'});
}else {
    $('.fixed-ct').css({'top':'0px','bottom':'auto'});
}

有时候由于底部200像素的原因,固定容器会在底部,但滚动时应该使用top:0px将其置于顶部,并且它应该在容器内部。


可能是Fixed position but relative to container的重复问题。 - Limbo
1
你尝试过使用 position: sticky 而不是 fixed 吗? - Daniel Bardaji Torres
我试过使用 position: sticky。但在Safari和一些旧浏览器中无法工作。 - user521024
2个回答

10

在 .fixed-ct 中使用 position:sticky,并在 .main-ct 中添加 position:relative。

.main-ct {
  width: 1000px;
  height:600px;
  border: 1px solid #000;
  position:relative;
}
.fixed-ct {
  position: sticky;
  width:100px;
  height:20px;
  background: red;
  top:10px;
}
.like-body {
  width: 100%;
  height:1300px;
}
<div class="like-body">
  <div class="main-ct">
    <div class="fixed-ct"></div>
  </div>
</div>


你能解释一下 position:sticky 是什么意思以及为什么它会这样工作,或者提供一个链接让回答更好吗? - Marvin
在用户开始滚动之前,如何使红色矩形向下更多地定位(而不是在左上角)? - Marvin
@Marvin sticky就像一个固定元素(position fixed),但是它在父容器内,你可以设置top属性,就像绝对定位的元素一样,在滚动时会保持在父元素内,模拟一个相对于其父元素固定位置的效果。请参见示例codepen - Teobis

0

CSS中的position:fixed属性是无法被其父元素控制的,它主要与浏览器的视口有关。因此你可以试着使用这个属性。

*body {
  margin: 0;
  padding: 0;
  outline: 0;
}

.container {
  width: 700px;
  margin: 0px 100px 0px 100px;
  padding-bottom: 2000px;
}

.main {
  width: 450px;
  height: 450px;
  background: rgba(228, 174, 201, .5);
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  overflow-y: scroll;
  position: absolute;
}

.header-fixed {
  background: rgba(255, 0, 0, 0.404);
  height: 50px;
  width: 450px;
  top: 0;
  position: sticky;
}

.body p {
  padding: 0px 20px 1000px 20px;
  text-align: justify;
  font-size: 20px;
  line-height: 40px;
}

.contact {
  background: rgba(12, 146, 236, 0.3);
  bottom: 20px;
  left: 300px;
  position: sticky;
  display: inline;
  padding: 10px;
  border-radius: 5px;
}
<div class="container">
  <div class="main">
    <div class="header-fixed"></div>
    <div class="body">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab voluptas est repellendus entore sit quaerat ratione architecto quos molesti a quis nisi! Veniam cum hic cumque?</p>
      <h2 class="contact">Call Now!</h2>
    </div>
  </div>
</div>


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