添加Logo后Navbar上下出现空白,寻求CSS解决方法
我想要制作带有Logo的Navbar,但添加height或width属性后,Navbar上下出现了空白。有没有可用的CSS属性可以解决这个问题?
这样看起来效果很差。
- 无Logo的Navbar截图
- 带Logo的Navbar截图
HTML代码
<section id="header"> <a class="name" href="#header" >SYNCC <img src="images/logo.png" alt="" height="90" class="logo-png" /></a> <div> <ul id="navbar"> <li><a class="active" href="#hero">Home</a></li> <li><a href="#feature">Features</a></li> <li><a href="#about">About Us</a></li> <li><a href="#footer">Contact</a></li> <li> <a href="#carouselExampleControls" ><i class="fa-solid fa-cart-shopping"></i ></a> </li> </ul> </div> </section>
CSS代码
#header { display: flex; align-items: center; justify-content: space-between; padding: 20px 80px; background: #E5E6EE; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.06); z-index: 999; position: sticky; top: 0; left: 0; right: 30%; } #navbar { display: flex; align-items: center; justify-content: center; } #navbar li { list-style: none; padding: 0 20px; position: relative; } #navbar li a { text-decoration: none; font-size: 16px; font-weight: 600; color: #1a1a1a; } .name { font-family: "DynaPuff", cursive; text-decoration: none; font-size: 25px; font-weight: 400; color: #1a1a1a; position: relative; top: 10px; } .name:hover, .name a { color: #088178; transition: 0.3s ease; } .name a::after, .name a:hover { content: ""; width: 30%; height: 2px; background: #088178; position: absolute; bottom: -4px; left: 20px; } #navbar li a:hover, #navbar li a.active { color: #088178; transition: 0.3s ease; } #navbar li a.active::after, #navbar li a:hover::after { content: ""; width: 30%; height: 2px; background: #088178; position: absolute; bottom: -4px; left: 20px; }
解决方法
1. 移除.name的偏移定位
你给.name设置了position: relative; top:10px;,这会让文字和Logo整体上移,迫使header容器预留额外空间,直接删除top:10px即可消除部分空白。
2. 修正图片的垂直对齐
图片默认是行内元素,会和文字基线对齐产生额外间距,给.logo-png添加以下样式:
.logo-png { display: inline-block; vertical-align: middle; /* 建议把行内的height属性移到这里统一控制 */ height: 90px; }
3. 调整header的padding值
当前padding:20px 80px和Logo高度叠加后可能导致容器过高,可适当缩小上下padding,比如改成padding:10px 80px,让Navbar高度更紧凑。
4. 修复伪元素的选择器错误
你的CSS里.name a::after是错误的,因为.name本身就是a标签,应该改成.name::after,否则伪元素不会生效,还可能干扰布局:
.name:hover::after { content: ""; width: 30%; height: 2px; background: #088178; position: absolute; bottom: -4px; left: 0; }
内容的提问来源于stack exchange,提问作者Rayan Sunu
相关产品推荐
相关产品推荐

