位置:粘性不起作用:第一个孩子选择器,发生了什么?

时间:2018-01-11 14:52:45

标签: css css-position sticky

问题是,我已经看到这在其他地方工作。所以它应该工作。我无法理解错误,因为浏览器开发工具显示该位置设置为粘性,但它并不坚持。

的jsfiddle https://jsfiddle.net/Slava_B/qr9tpLmh/



.parent {
  height: 1000px;
  width: 200px;
  position: relative;
  display: inline-block;
}

.position-sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background: rgba(200, 220, 255, 0.5);
}

.position-first-child-sticky {
  position: relative;
}

.position-first-child-sticky> :first-child {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background: rgba(255, 220, 200, 0.5);
}

<div class="parent">
  <div class="position-sticky">I'm sticky</div>
</div>
<div class="parent">
  <div class="position-first-child-sticky">
    <div>I'm fist-child-sticky</div>
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

这是因为您的子元素 .position-first-child-sticky > :first-child 及其父容器 .position-first-child-sticky 在DOM中占据相同的高度。

  

A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold, at which point it is treated as fixed.

尝试在 .position-first-child-sticky 上添加一些高度,您会看到差异。

&#13;
&#13;
.parent {
  height: 1000px;
  width: 200px;
  position: relative;
  display: inline-block;
}

.position-sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background: rgba(200, 220, 255, 0.5);
}

.position-first-child-sticky {
  position: relative;
  height: 200px;
}

.position-first-child-sticky> :first-child {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background: rgba(255, 220, 200, 0.5);
}
&#13;
<div class="parent">
  <div class="position-sticky">I'm sticky</div>
</div>
<div class="parent">
  <div class="position-first-child-sticky">
    <div>I'm fist-child-sticky</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

问题似乎是没有将高度添加到.position-first-child-sticky。如果您设置此1000px的高度,那么它可以正常工作。高度也可以设置为inherit

.position-first-child-sticky {
height: 1000px;
}

这是一个有效的例子:

.parent{
  height: 1000px;
  width:200px;
  position:relative;
  display:inline-block;
}
.position-first-child-sticky {
height: 1000px;
}
.position-sticky{
  position:-webkit-sticky;
  position:sticky;
  top:0;
  background:rgba(200,220,255,0.5);
}
.position-first-child-sticky{position:relative;}
.position-first-child-sticky > :first-child{
  position:-webkit-sticky;
  position:sticky;
  top:0;
  background:rgba(255,220,200,0.5);
 }
<div class="parent">
  <div class="position-sticky">I'm sticky</div>
</div>
<div class="parent">
  <div class="position-first-child-sticky">
    <div>
      I'm fist-child-sticky
    </div>
  </div>
</div>