首页 > 解决方案 > 固定顶部导航不覆盖页面内容

问题描述

我正在尝试创建一个顶部固定的导航,如果需要,它应该始终可见并覆盖内容。但是,经过几次尝试,我得到了以下结果。我想摆脱导航栏上的这种“透明度”效果。

@import url("https://fonts.googleapis.com/css?family=Montserrat+Alternates:400,800|Poppins");
.nav-title {
  font-family: 'Montserrat Alternates', sans-serif;
  font-weight: 800;
  font-size: 1.5rem;
}

#mobile-nav {
  height: 3.8rem;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 1rem;
  box-shadow: 0px 1px 10px black;
}
#mobile-nav i {
  font-size: 3rem;
}

#content {
  margin-top: 4rem;
}

#start {
  height: 50vh;
  width: 100%;
  font-family: 'Poppins', sans-serif;
  text-align: center;
}
#start h1 {
  position: relative;
  top: 25%;
  font-size: 2.3rem;
  margin: 0 1rem;
}

#info {
  height: 100vh;
  width: 100%;
  font-family: 'Poppins', sans-serif;
  margin: 0 auto;
  text-align: c;
}
#info p {
  margin: 0 50px;
}
#info h2 {
  text-align: center;
}

.fixed-top {
  position: fixed;
  top: 0;
}
<header>
  <nav id="mobile-nav" class="fixed-top">
    <div class="nav-title">Some logo</div>
    <i class="material-icons">menu</i>
  </nav>
</header>

<div id="content">
  <section id="start">
    <h1>This is an<br />awesome header.</h1>
  </section>
  <section id="info">
    <h2>And this is another header.</h2>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum condimentum nibh vel eros porttitor semper. Sed sit amet porttitor velit, sed malesuada orci. Nam nec gravida quam. Proin eget tristique quam. Nam posuere massa magna. Aenean congue
      sed enim id tempus. Etiam sed est in arcu facilisis auctor sit amet nec eros. Duis cursus molestie quam, quis blandit ex eleifend vitae. Quisque efficitur leo at magna ornare, vitae aliquam ante interdum. Nullam eget consectetur arcu. Suspendisse
      sit amet tincidunt dui, sit amet placerat nunc. Sed posuere, lacus quis pellentesque interdum, dui nulla molestie est, vel condimentum enim quam in ex.</p>

到目前为止,我已经尝试过 z-index 并将 margin-top 添加到内容 div 但这并没有成功。我做错了什么,我该如何解决?固定位置有什么具体的事情吗?

标签: htmlcsslayoutcss-positionnavbar

解决方案


background-color如果你想让它不透明,你需要给它一个。此外,因为它在其余内容之前,所以当它们重叠时,其余内容将在它之上。把它带到上面,给它z-index: 1

.fixed-top {
  position: fixed;
  top: 0;
  background-color: white;
  z-index: 1
}

另一种方法是将滚动条从 移动body#content,这将不再允许它们重叠(在这种情况下,您不再需要上述内容)。它还具有不在菜单顶部呈现滚动条的优点:

#content {
  margin-top: 4rem;
  max-height: calc(100vh - 4rem);
  overflow-y: auto;
}

padding最后,您应该通过告诉它包含在其总width计算中来防止顶部栏超过文档的宽度:

#mobile-nav {
  box-sizing: border-box;
}

在这里看到它:https ://codepen.io/andrei-gheorghiu/pen/KbbmmG


推荐阅读