垂直菜单需设flex-direction: column,配合justify-content(space-between/space-around/space-evenly)实现不同“均匀”效果,并用align-items: center水平居中,优先min-height防溢出。

flex-direction: column 是垂直布局的前提
默认 display: flex 是水平排列(flex-direction: row),要让菜单项从上到下排,必须显式设为列方向。只加 display: flex 不够,漏掉这步菜单还是横着的。
-
flex-direction: column必须写在容器(比如或)上 - 如果容器有固定高度(如
height: 100vh),才能配合justify-content: space-between或space-around实现“均匀分布” - 别在菜单项(
或)上乱设flex,容易破坏主轴对齐逻辑
justify-content 控制项间间距类型
垂直菜单里“均匀分布”通常指项与项之间空隙相等,但顶部、底部是否留空要看选哪个值:
-
justify-content: space-between:首项顶边、末项底边贴容器边界,中间空隙均分 -
justify-content: space-around:每项上下各占一半间距,视觉上更“居中松散” -
justify-content: space-evenly:所有间隙(含首项前、末项后)完全相等,最符合字面“均匀” - 用
align-items: center可让所有菜单项水平居中(避免文字靠左挤成一竖条)
别忽略 min-height 和 overflow 隐患
当菜单项变多或字体放大时,容器可能撑不开,导致内容被截断或溢出:
- 避免只设
height,优先用min-height(如min-height: 100vh)保底 - 如果菜单项动态增减,
justify-content: space-evenly在项少时会拉得过开,此时改用flex-wrap: wrap+align-content: center反而更稳 - 移动端小屏下建议加
overflow-y: auto,不然超长菜单直接消失不见
一个可用的最小代码骨架
nav {
display: flex;
flex-direction: column;
min-height: 100vh;
justify-content: space-evenly;
align-items: center;
}
nav a {
padding: 0.75rem 1.5rem;
text-decoration: none;
color: #333;
}
注意:如果导航用的是 结构,记得先清掉 ul 默认的 padding-left 和 margin,否则左侧会多出空白。
立即学习“前端免费学习笔记(深入)”;
真正难的不是写这几行 CSS,而是判断“均匀”到底指什么——是项之间等距?还是项+上下边距整体等分?不同场景得换不同的 justify-content 值,不能套模板硬上。









