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

标签 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 中添加了虚拟数据,使其能够上下滚动。

最佳答案

A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.

考虑到这一点,我们知道我们需要满足阈值,这意味着 top:0 意味着当 #menubar 从其包含 block 的顶部开始偏移为 0 .

在我们的例子中,包含 block 是 #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 的布局方式,我演示了其中一个,因为我不知道哪个更适合您,可能更改标记不是选项。

关于html - 为什么粘性位置在子 div 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53131200/

相关文章:

javascript - 基于鼠标点击位置的鼠标悬停弹窗

css - 使菜单居中,左对齐元素

html - 如何调整图像大小以适合另一幅图像?

javascript - 当使用 javascript 设置父宽度时,在子 div 周围设置边距

css - 你能用 AngularJS 做条件格式化吗?

javascript - 谁能解释一下音频标签中的这段JS代码吗?

html - 将同一链接工作表中的 CSS 元素更改为 2 个 html 文件

CSS3 Transform 只播放第一项

HTML 如何使表格的每一行都可滚动?

javascript - 从 EJS 中的日期对象切片时间戳 - Javascript、HTML、Node.js