位置:粘性不适用于顶级属性? [英] position: sticky is not working with top property?

查看:69
本文介绍了位置:粘性不适用于顶级属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

位置:底部粘:10px上div,类侧边栏按预期工作但是属性顶部:10px没有按预期工作?

Position: sticky with bottom:10px on div with class sidebar is working as expected but with property top:10px is not working as expected?

位置:粘性底部:带有类侧边栏的div上10px,当我们向下滚动div棒以查看端口高于10px的端口到视口时。

With position: sticky with bottom: 10px on div with class sidebar, when we scroll down the div stick to view port with a bottom edge above 10px to the view port.

与位置类似:粘贴顶部:带有类侧边栏的div上10px,因为我们向上滚动div应该粘在顶部,在视口下方div 10px的上边缘。

Similarly with position: sticky with top:10px on div with class sidebar, as we scroll up the div should stick to top with the top edge of div 10px below the viewport.

但它是不这样做,有什么问题?

But it is not working this way, what is the problem?

代码: 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>

推荐答案

在我的情况下,粘性元素的父级(侧边栏)的高度小于内容=>粘性元素的下降不超过侧边栏的高度。

In my case, the parent of the sticky element (the sidebar) had a smaller height than the content => the sticky element wasn't going down more than the sidebar's height.

解决方案:我使侧边栏的高度等于内容的高度(在内容和侧边栏的包装上使用display flex)。

The solution: I made the sidebar's height equal to the content's height (using display flex on the content's and sidebar's wrapper).

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

这篇关于位置:粘性不适用于顶级属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆