【问题标题】:How do I keep position: relative content from overlapping my position: sticky header?如何保持位置:相对内容与我的位置重叠:粘性标题?
【发布时间】:2020-01-13 13:26:22
【问题描述】:

我有一个粘性顶部导航栏,我希望在滚动时保持可见并且高于所有其他内容。我将页面上的内容设置为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>

预期:粘性标题高于所有其他内容。

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

【问题讨论】:

标签: html css css-position overlapping


【解决方案1】:

如果您希望您的导航栏始终可见,只需给它一个比您的内容更大的 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
}

【讨论】:

  • 为什么是 z-index?它会弄乱图层
【解决方案2】:

试试这个。从 .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>

【讨论】:

    【解决方案3】:

    您可以使用此代码

    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;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多