导航栏中Material Symbol图标与文本垂直对齐失效问题
Material Symbol图标与导航文本垂直对齐问题
我正在开发一个导航栏,尝试将Material Symbol图标与文本垂直对齐,但始终无法实现。目前图标与文本未垂直对齐(效果:图标明显高于右侧的文本,未处于同一垂直线上)。已在.navbar-item类中使用align-items:center属性,理论上应能垂直对齐子元素,但并未生效,请问遗漏了什么?
我的代码
HTML代码
<ul class="navbar-items-list"> <li class="navbar-item"><a href="#"><span class="material-symbols-outlined size-32">Home</span> Home</a></li> <li class="navbar-item"><a href="#">About</a></li> <li class="navbar-item"><a href="#">Services</a></li> <li class="navbar-item"><a href="#">Contact</a></li> <li class="navbar-item"><a href="#">Blog</a></li> </ul>
CSS样式
.navbar-items-list { display: flex; flex-direction: column; justify-content: start; align-items: center; list-style: none; padding: 0; margin: 5rem 0 0 0; } .navbar-item { display: flex; align-items: center; width: 100%; padding: 1rem 2rem; font-size: 0.8rem; color: $white; text-decoration: none; border-top: 1px solid rgba($color: $white, $alpha: 0.1); transition: all 0.3s ease; } .navbar-item a { color: $white; font-size: 0.8rem; font-weight: 700; text-decoration: none; width: 100%; height: 100%; display: block; }
Material Symbol尺寸设置
span.size-32 { font-size: 32px; font-variation-settings: 'OPSZ' 32; }
图标引入方式
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght@100" rel="stylesheet" />
问题原因
你设置的.navbar-item是flex容器且align-items: center,但它的直接子元素是<a>标签,而<a>被设置为display: block——这意味着图标和文本都在这个块级的<a>内部,.navbar-item的对齐规则只能作用于<a>整体,无法影响其内部元素的垂直位置。
解决方案
修改.navbar-item a的布局属性,让它成为flex容器,从而控制内部图标和文本的垂直对齐:
.navbar-item a { color: $white; font-size: 0.8rem; font-weight: 700; text-decoration: none; width: 100%; height: 100%; /* 修改为flex布局 */ display: flex; /* 垂直居中内部元素 */ align-items: center; /* 可选:给图标和文本添加间距 */ gap: 0.5rem; }
另外,若图标仍有轻微偏移,可以给Material Symbol的span标签添加line-height: 1,消除字体自带的行高影响:
span.size-32 { font-size: 32px; font-variation-settings: 'OPSZ' 32; line-height: 1; }
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

