本文详解如何用 css flexbox 实现水平居中的响应式导航栏,通过 `justify-content: space-around` 均匀分配菜单项间距,并为链接添加从左到右的平滑下划线悬停动画。
要实现导航栏在页面中水平居中、各菜单项(About / Experience / Works / Hobbies)之间保持均匀间距,并支持优雅的悬停下划线动画,核心在于正确应用 Flexbox 布局层级。
问题根源在于:原代码中 .nav li 设置了 display: inline-flex,但 justify-content: space-around 并未生效——因为该属性仅对 Flex 容器(flex container) 有效,而真正需要布局的是
- 元素(其子元素
- 才是直接参与排列的 flex items)。因此,必须将 display: flex 应用于
- ,而非
- 。
以下是优化后的完整解决方案:
✅ 正确的 CSS 结构(关键修改已高亮)
* { box-sizing: border-box; /*
修正原代码拼写错误:ox-sizing → box-sizing */
margin: 0;
padding: 0;
}
body {
background-color: #333;
color: #fff;
font-family: 'Kalam', cursive;
}
header {
padding: 1.5rem 0; /* 增加上下内边距,提升视觉呼吸感 */
}
/* ✅ 关键:将 ul 设为 flex 容器,实现居中与 spacing */
.nav ul {
display: flex;
justify-content: space-around; /* 均匀分配项间及边缘空白 */
align-items: center; /* 垂直居中对齐(兼容不同行高) */
list-style: none; /* 移除默认圆点 */
margin: 0;
padding: 0;
}
.nav a {
text-decoration: none;
color: #fff;
font-size: 1.1rem;
padding: 0.5rem 0.8rem; /* 可选:为点击区域增加内边距 */
position: relative;
transition: color 0.2s ease; /* 可选:文字颜色过渡更柔和 */
}
/* 下划线动画:绝对定位 + 宽度过渡 */
.nav a::after {
content: "";
display: block;
height: 3px;
width: 0;
background-color: #fff;
transition: width 0.3s ease-in-out;
position: absolute;
bottom: 0;
left: 0;
}
.nav a:hover::after {
width: 100%;
}
/* ✅ 移除 .nav li 的 inline-flex —— 它现在是 flex item,无需自身 flex */
.nav li {
list-style: none; /* 仅清除列表符号,不干扰 flex 布局 */
}? 注意事项与进阶建议
- 拼写修正:原代码中 ox-sizing 是明显笔误,必须改为 box-sizing,否则重置样式失效。
- 语义化增强:可将 替换为
- 。

修正原代码拼写错误:ox-sizing → box-sizing */
margin: 0;
padding: 0;
}
body {
background-color: #333;
color: #fff;
font-family: 'Kalam', cursive;
}
header {
padding: 1.5rem 0; /* 增加上下内边距,提升视觉呼吸感 */
}
/* ✅ 关键:将 ul 设为 flex 容器,实现居中与 spacing */
.nav ul {
display: flex;
justify-content: space-around; /* 均匀分配项间及边缘空白 */
align-items: center; /* 垂直居中对齐(兼容不同行高) */
list-style: none; /* 移除默认圆点 */
margin: 0;
padding: 0;
}
.nav a {
text-decoration: none;
color: #fff;
font-size: 1.1rem;
padding: 0.5rem 0.8rem; /* 可选:为点击区域增加内边距 */
position: relative;
transition: color 0.2s ease; /* 可选:文字颜色过渡更柔和 */
}
/* 下划线动画:绝对定位 + 宽度过渡 */
.nav a::after {
content: "";
display: block;
height: 3px;
width: 0;
background-color: #fff;
transition: width 0.3s ease-in-out;
position: absolute;
bottom: 0;
left: 0;
}
.nav a:hover::after {
width: 100%;
}
/* ✅ 移除 .nav li 的 inline-flex —— 它现在是 flex item,无需自身 flex */
.nav li {
list-style: none; /* 仅清除列表符号,不干扰 flex 布局 */
}






