求助:作品集网站Navigation bar与内容重叠问题排查
导航栏与页面内容重叠的解决方案
问题说明
制作个人作品集网站时,固定定位的导航栏始终和页面其他内容重叠,添加margin也无法解决,只能靠手动换行规避。
用户提供的原始效果:
问题根源
导航栏使用了position: fixed,这个属性会让元素脱离正常文档流,不再占据页面空间,所以页面后续内容会直接跑到导航栏下方导致重叠。另外给.nav-bar添加的margin-bottom对脱离文档流的元素无效,给title标签加样式也没有意义——title是头部标签,不会在页面中显示。
修复方案
- 给导航栏设置明确高度(或用内边距撑开高度)
- 给
body或页面主内容容器添加等于或大于导航栏高度的上边距,让内容避开导航栏区域
修改后的CSS代码
@import url('https://fonts.googleapis.com/css2?family=Poppins&family=Quicksand&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; } body { background-color: black; color: whitesmoke; font-family: 'Quicksand', sans-serif; /* 添加上边距,避开导航栏 */ padding-top: 80px; } .nav-bar { width: 100%; position: fixed; font-family: 'Poppins', sans-serif; margin-left: 40px; margin-top: 3px; /* 去掉无效的margin-bottom */ display: block; /* 设置导航栏高度,方便计算内容上边距 */ height: 70px; } .nav-bar a { color: white; text-decoration: none; } .nav-bar li { list-style: none; display: inline-block; margin: 0 20px } .nav-bar a:hover { text-decoration: underline; text-decoration-color: #FFDD93; transition: 1s; } .home-icon:hover { text-decoration: underline; text-decoration-color: #FFDD93; transition: 1s; } ul { font-size: 2.5rem; }
修改后的HTML代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Aman Nambisan</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="styles.css"> <link href="https://fonts.googleapis.com/css2?family=Poppins&family=Quicksand&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <nav class="nav-bar"> <div class="nav-bar-div"> <ul class="menu"> <li><a href="#"><i class="fa fa-home home-icon" style="font-size:48px"></i></a></li> <li><a href="#">About</a></li> <li><a href="#">Education</a></li> <li><a href="#">Skills</a></li> <li><a href="#">Contact me</a></li> </ul> </div> </nav> <p> hello </p> <script src="index.js" async defer></script> </body> </html>
额外说明
- 固定定位元素脱离文档流,自身的
margin/padding不会影响其他元素布局,必须通过给后续内容预留空间来避免重叠 - 如果是响应式布局,导航栏高度可能动态变化,可以用JavaScript实时计算导航栏高度,再设置内容的上边距;静态布局下直接设置固定值即可满足需求
内容的提问来源于stack exchange,提问作者Aman Nambisan
相关产品推荐
相关产品推荐

