为什么粘性位置在子div中不起作用

时间:2018-11-03 12:16:13

标签: html css

我在html页面中有多个div。当我尝试粘贴菜单栏时,它不起作用,并且菜单栏位于其他div内。这是我的代码。

#menubar {
  height: 50px;
  width: 100%;
  background-color: red;
  position: -webkit-sticky;
  position: sticky;
  top: 0
}

.content {
  /* to mimic content so we can have scroll */
  height: 1000px;
}
<div id="container">
  <div id="header">
    <div id="bannerbox">
      <img src="https://via.placeholder.com/300x300" height="100%" width="100%" />
    </div>
    <div id="menubar">
      <ul>
        <li> <a href="#">Home</a></li>
        <li> <a href="#">Home</a></li>
        <li> <a href="#">Home</a></li>
      </ul>
    </div>
    <div id="cityinfo">
    </div>
  </div>
  <div id="content" class="content">

  </div>
  <div id="footer">
  </div>
</div>

哪里做错了?我什至尝试了很多方法,但是没有用。

我在内容div中添加了虚拟数据,以使其能够上下滚动。

1 个答案:

答案 0 :(得分:0)

  

A stickily positioned element 是其计算出的位置值为粘性的元素。它被视为相对定位,直到其包含的块在其流根(或在其中滚动的容器)内超过指定的阈值(例如,将top设置为auto以外的值),在该点处将其视为“卡住”,直到达到其包含块的相对边缘。

请牢记这一点,我们知道需要满足我们的阈值,这意味着top:0表示#menubar与其包含的块的顶部偏移0。

在我们的例子中,包含块是#header,它的高度是由其内容定义的,因此永远不会达到阈值,因为其中没有溢出/滚动。

为了更清楚地看到这一点,我们可以应用一些高度。

#menubar {
  height: 50px;
  width: 100%;
  background-color: red;
  position: sticky;
  /* when there's 10px space left between menubar and header */
  /* make it stick */
  top: 10px;
}

#header {
  border: 5px solid lime;
  height: 1000px;
}

.content {
  border: 5px solid orange;
  height: 1000px;
}
<div id="container">
  <div id="header">
    <div id="bannerbox">
      <img src="images/banner.png" height="100%" width="100%" />
    </div>
    <div id="menubar">
      i'm stuck sticky
    </div>
    <div id="cityinfo">cityinfo</div>
  </div>

  <div id="content" class="content">
    header height is almost done, so the threshold will not be met very soon, this is what's hapening when the header has no overflow/scroll, menubar becomes sticky and goes back to normal almost instantly perhaps it never happens we don't know, it depends
    on how the user agant handles it.
  </div>
  <div id="footer"></div>
</div>

解决方法是使标头全部粘在一起或更改html的布局方式,我演示了它们中的任何一个,因为我不知道哪个更适合您,可能更改标记不是选项。

相关问题