问题是,我已经看到这在其他地方工作。所以它应该工作。我无法理解错误,因为浏览器开发工具显示该位置设置为粘性,但它并不坚持。
的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;
答案 0 :(得分:3)
这是因为您的子元素 .position-first-child-sticky > :first-child
及其父容器 .position-first-child-sticky
在DOM中占据相同的高度。
尝试在 .position-first-child-sticky
上添加一些高度,您会看到差异。
.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;
答案 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>