如何避免position为relative的内容重叠在position为sticky的页眉上?

15

我有一个固定在页面顶部的导航栏,希望在滚动时保持可见并在所有其他内容之上。页面上的某些内容我已经设置为position: relative,以便我可以在其周围定位其他元素。但是这样做会导致相对位置的内容在滚动时忽略导航栏并重叠在其上。是否有办法使我的页面内容相对定位时仍然遵守固定导航栏呢?

我尝试给相对位置的内容添加一个等于导航栏高度的顶部边距。

.nav-bar {
  position: sticky;
  top: 0px;
  font-family: Arial, Helvetica, sans-serif;
  border-bottom: solid rgb(179, 173, 173) 1px;
  background-color: rgb(255, 255, 255);
}

.nav-bar #title {
  margin: 0;
  font-size: 2em;
  padding-left: 2%;
}

.test-class #test-content {
  width: 500px;
  height: 500px;
  background-color: rgb(70, 67, 67);
  position: absolute;
}
<div class="nav-bar">
  <p id="title">Title</p>
</div>
<div class="test-class">
  <p id="test-content"></p>
</div>

期望: 粘性标题应保持在所有其他内容之上。

实际: 当其位置设置为相对位置时,内容会重叠标题。


1
你的代码中没有设置任何元素的 position: relative - Quentin
请提供一个 [mcve] 来演示您所描述的问题,并使用 live demo feature - Quentin
请更新您的代码片段,以便它能够重现您的问题。 - G-Cyrillus
z-index是你的好朋友。 - 0b10011
3个回答

11
如果您希望您的导航栏始终可见,只需为其设置比内容更大的z-index即可。
.nav-bar{
    position:sticky;
    top:0px;
    font-family: Arial, Helvetica, sans-serif;
    border-bottom:solid rgb(179, 173, 173) 1px;
    background-color: rgb(255, 255, 255);
    z-index: 1
}

1
为什么要使用 z-index?因为它可以搞乱图层。 - MartianMartian
1
大家都不想要的最悲伤的解决办法... :( - undefined
大家都不想要的最悲伤的解决办法... :( - José Antonio Postigo

1
尝试这个。从.test-class #test-content类中删除position:absolute。它可以像你想要的那样正常工作。

.nav-bar{
    position:sticky;
    top:0px;
    font-family: Arial, Helvetica, sans-serif;
    border-bottom:solid rgb(179, 173, 173) 1px;
    background-color: rgb(255, 255, 255);
}

.nav-bar #title{
    margin:0;
    font-size: 2em;
    padding-left: 2%;
}

.test-class #test-content {
    width:500px;
    height:500px;
    background-color:rgb(70, 67, 67);
}
<body>
    <div class="nav-bar">
        <p id="title">Title</p>
    </div>
    <div class="test-class">
        <p id="test-content"></p>
    </div>
</body>


0

你可以使用这段代码

body {
        margin: 0;
        padding: 0;
    }
    .nav-bar {
        overflow: hidden;
        background-color: #333333;
        position: sticky;
        top: 0;
        width: 100%;
    }
    .nav-bar #title {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 20px;
        text-decoration: none;
        font-size: 25px;
        margin: 0;
    }
    .test-class {
        padding: 16px;
        margin-top: 0px;
        height: 1500px;
    }
    .test-class #test-content {
        width: 500px;
        height: 500px;
        background-color: rgb(70, 67, 67);
        margin: 0;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接