html - 固定顶部导航不覆盖页面内容
问题描述
我正在尝试创建一个顶部固定的导航,如果需要,它应该始终可见并覆盖内容。但是,经过几次尝试,我得到了以下结果。我想摆脱导航栏上的这种“透明度”效果。
@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 但这并没有成功。我做错了什么,我该如何解决?固定位置有什么具体的事情吗?
解决方案
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;
}
推荐阅读
- javascript - vue切换标签页无法在第二个上显示相同的EChart表单(已修复)
- python - 如何从递归字典检查中返回差异量
- javascript - 更改切换状态时如何删除会话存储?
- docker - 无法启动我的 Docker 容器并给我一个 shell
- java - 获取 aws com.amazonaws.SdkClientException 的 PKIX 路径构建失败
- qt - 延迟发射信号
- javascript - Javascript:如何从页面获取图像字节(无需重新下载)
- angular - 如何在角度服务文件中的值更改上使用异步管道触发 api 调用?
- scala - 如何使用 scala/python/spark 在 CSV 文件中创建新的时间戳(分钟)列
- linux - 在 shell 脚本中运行 oracle 查询