【问题标题】:Have sticky navbar positioned after absolutely positioned div在绝对定位的 div 之后定位粘性导航栏
【发布时间】:2019-05-10 13:21:06
【问题描述】:

我有一个 div,它打算占据初始屏幕的 100%,需要左右浮动。因此,我必须将 div = 设置为,以便浮动元素可以占据 100% 的屏幕。我现在尝试在其他 div 之后添加,但这不起作用,因为导航栏不在绝对定位的元素下。

<div id = "top-news">
         <div id = "top-logo">
            <img src = "assets/logo.png" />
          </div>
          <div id = "focused-story">
            <img src = "assets/clinton.jpg" />
          </div>
          <div id = "story-carousel">
            <ul>
              <a href = "#"><li>First story</li></a>
              <a href = "#"><li>Second story</li></a>
              <a href = "#"><li>Third story</li></a>
              <a href = "#"><li>Fourth Story</li></a>
              <a href = "#"><li>Fifth Story</li></a>
            </ul>
          </div>
        </div>

上面是绝对定位的代码段,blow 是导航栏

      <nav id = "navbar">
        <img src = "assets/logo.png" />
      </nav>

这是定位所有内容的相关 css

#top-news
{
  width: 100%;
  height: 100%;
  overflow: auto;
  position: absolute;
}

#top-logo
{
  width: 100px;
  background-color: #d3d3d3;
  border-bottom-right-radius: 50px;
  border-bottom-left-radius: 50px;
  position: absolute;
  left: calc(50% - 50px);
}

#top-logo img
{
  width: 65px;
  margin: 0 auto;
  margin-left: 14.5px;
  padding: 5px;
}

#focused-story
{
  width: 50%;
  height: 100%;
  float: left;
  background-color: blue;
}

#story-carousel
{
  width: 50%;
  height: 100%;
  float: right;
  background-color: #f6f3ed;
  display: flex;
  align-items: center;
}

#navbar
{
  position: sticky;
  top: 100%;
  width: 100%;
  background-color: #d3d3d3;
  height: 50px;
}

我认为这会导致导航栏定位在下一页上,但它只是与绝对 div 重叠,因为它已从流程中取出。有没有办法解决这个问题?

【问题讨论】:

    标签: html css


    【解决方案1】:

    我的建议是将margin-top 添加到100vh#navbar(vh = 视口高度)。这将允许您考虑文档流之外的绝对定位元素。

    还要确保 #top-news 有一个 top: 0 以确保它位于文档顶部。

    希望对您有所帮助。

    【讨论】:

    • 感谢 Mendel 这个作品,我会支持你,但显然我没有足够的声誉这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多