position: sticky属性与top属性无法正常工作?

4

.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>


现在的问题是,使用position: sticky和bottom: 0px时无法生效。我们的目标是让position: sticky和bottom: 0px以及top: 0px同时生效。 - Rahul
好的,我正在尝试制作类似于Flipkart侧边栏的侧边栏(其中包含筛选器和价格范围),看起来它是采用粘性定位? - Rahul
你能建议一下如何制作吗? - Rahul
是的!因为 div 是块级元素,如果我们不使用 inline-block,它将会在另一个 div 下方流动!但不是100%确定。 - Rahul
看得很清楚!我会使用flex,这里有一个简单的模板(克隆,向下滚动以获取顶部和底部)https://codepen.io/gc-nomade/pen/mMJmRB - G-Cyrillus
显示剩余7条评论
1个回答

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

谢谢你的回答,但请同时包含你的代码。使用 CSS 示例,你的答案将更有助于其他人。 - sertsedat
1
我编辑了我的回答。请告诉我这是否是你正在寻找的解决方案。 - TheoPlatica

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