位置:粘性不适用于顶级属性?

问题描述 投票:3回答:1

位置:粘底:10px在div上,类边栏正在按预期工作但是属性顶部: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>
javascript jquery html css css3
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; }
© www.soinside.com 2019 - 2024. All rights reserved.