HTML/CSS开发中如何正确定位图标与顶部导航栏
问题根源
- 给导航栏设置
position: fixed后未明确指定top、left偏移值,不同浏览器内核渲染时定位基准不统一,导致顶部间距不符合预期 - 导航栏内的铃铛图标未设置网格对齐规则,出现垂直/水平位置偏移
- 固定定位的导航栏脱离普通文档流,下方侧边栏、主内容区没有预留对应高度的顶部间距,会被导航栏遮挡
修复代码
直接替换原有CSS即可:
* { padding: 0; margin: 0; box-sizing: border-box; font-family: 'poppins', sans-serif; } .topbar { position: fixed; /* 固定到视口顶部,如需顶部留空隙把0改成对应像素值即可,比如top: 10px */ top: 0; left: 0; background: #fff; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.08); width: 100%; height: 60px; padding: 0 20px; display: grid; grid-template-columns: 2fr 10fr 0.4fr 1fr; align-items: center; z-index: 1; } /* 导航栏铃铛图标对齐 */ .topbar .fa-bell { justify-self: center; font-size: 20px; cursor: pointer; } .logo h2 { color: #df7f27; } .search { position: relative; width: 60%; justify-self: center; } .search input { width: 100%; height: 40px; padding: 0 40px; font-size: 16px; outline: none; border: none; border-radius: 10px; background: #f5f5f5; } .search i { position: absolute; right: 15px; top: 15px; cursor: pointer; } .user { position: relative; width: 50px; height: 50px; justify-self: end; } .user img { position: absolute; top: 0; left: 0; height: 100%; width: 100%; object-fit: cover; border-radius: 50%; } /* 给下方内容预留导航栏高度,避免被遮挡 */ .sidebar, .main { padding-top: 60px; }
调整说明
如果需要导航栏和浏览器顶部保留固定间距,只需要修改.topbar的top属性值,同时把.sidebar和.main的padding-top值改成「60px + top属性设置的间距值」即可匹配目标布局。
内容的提问来源于stack exchange,提问作者pomoworko.com
相关产品推荐
相关产品推荐

