繁体   English   中英

如何保持位置:相对内容不重叠我的位置:粘性标题?

[英]How do I keep position: relative content from overlapping my position: sticky header?

我有一个粘性的顶部导航栏,在滚动时我想保持可见,并且位于所有其他内容之上。 我在页面上设置了以下内容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> 

预期:粘性标头停留在所有其他内容之上。

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

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

如果您想让导航栏始终保持可见状态,请给它一个大于内容的Z索引

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

您可以使用此代码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM