【问题标题】:why sticky position does not work in child div为什么粘性位置在子 div 中不起作用
【发布时间】:2019-04-07 10:38:48
【问题描述】:

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

【问题讨论】:

  • 需要div#menubar元素前后的一些内容才能看到sticky位置的效果。
  • @roshi pandy 在你的#menubar css 中使用position:fixed 而不是position:sticky
  • @ths 正如我上面提到的,粘性 div 有图像,粘性 div 下方有多达 100 行的内容,我在此处提问之前删除了这些内容
  • @Gaurav 我想使用不固定的粘性,因为菜单栏不在顶部,而是在页面中间
  • @roshipandy 我明白了,我按预期添加了一些内容和您的代码 wprks。 @Gaurav fixed 位置是相对于视口计算的,因此无法达到 OP 需要的效果。

标签: html css


【解决方案1】:

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 的布局方式,我演示了它们中的任何一个,因为我不知道哪个更适合您,可能更改标记不是选项。

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2019-07-20
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多