位置:底部是粘性的:带有类边栏的div上的10px按预期工作但是属性顶部:10px没有按预期工作?
位置:粘贴底部:带有类侧边栏的div上10px,当我们向下滚动div棒以查看端口高于10px的端口到视口时。
与位置类似:粘贴顶部:带有类侧边栏的div上的10px,当我们向上滚动时,div应该粘贴到顶部,并且视口下方的div 10px的上边缘。
但这不是这样的,问题是什么?
代码:https://jsfiddle.net/c7vxwc7g/
.container{
/*width: 1654px;*/
width: 100%;
background-color: #f0f0f0;
margin: 0 auto;
}
.sidebar{
position: sticky;
bottom: 10px;
width: 400px;
margin: 5px;
background-color: teal;
height: 1000px;
display: inline-block;
}
.mainpage{
width: 1130px;
margin: 5px;
margin-left: 0px;
background-color: steelblue;
height: 6000px;
display: inline-block;
}
.footer{
height: 500px;
width: 1654;
margin: 0 auto;
margin-top: 10px;
background-color: purple
}
.test1{
background-color: red;
position: relative;
left: 0;
right: 0;
top: 0;
height: 200px;
}
.test2{
background-color: red;
position: relative;
left: 0;
right: 0;
bottom: 0;
height: 200px;
}

<body>
<div class="container">
<div class="sidebar">
<div class="test1">test1</div>
<div class="test2">test2</div>
</div>
<div class="mainpage">mainpage</div>
</div>
<div class="footer">footer</div>
</body>
&#13;
答案 0 :(得分:1)
在我的情况下,粘性元素(边栏)的父级的高度小于内容的高度=>粘性元素的下降幅度不超过边栏的高度。
解决方案:我使边栏的高度等于内容的高度(在内容和边栏的包装器上使用display flex)。
HTML:
<div clas="container">
<div class="content">This initially has a bigger height than sidebar.</div>
<div class="sidebar">
<div class="sticky"></div>
</div>
</div>
CSS:
.container { dislay: flex; } // By using this I make the sidebar the same height as the content
.sticky { position: sticky; top: 0; }