当使用 `display: flex` 的导航栏中需让标题(如 `
tent: space-between` 下的 `flex-grow`,而应通过绝对定位或脱离文档流的方式实现真正的视口级居中。在典型的 Flex 导航栏结构中(如 header { display: flex; justify-content: space-between }),三个子元素——左侧导航、中间标题、右侧按钮——会按顺序分配空间。此时即使为
要实现「标题始终位于屏幕正中央」,核心思路是:让标题脱离 Flex 主轴的布局约束,直接基于视口定位。推荐方案如下:
header {
position: relative; /* 为绝对定位提供参照 */
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 2%;
height: 80px; /* 显式高度便于垂直居中 */
}
.nav-logo {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
pointer-events: none; /* 避免遮挡下方 nav/button 的交互 */
}
.nav-logo h1 {
margin: 0;
font-size: 1.5rem;
pointer-events: auto; /* 恢复标题自身可交互性(如点击) */
}SalonM
? 关键点说明:.nav-logo 使用 position: absolute 脱离 Flex 流,宽度设为 100% 并 justify-content: center,确保 始终居中于整个视口宽度;pointer-events: none 是重要细节:避免绝对定位层阻挡下方 和 的鼠标事件(如点击菜单项或按钮);height: 100% 与 align-items: center 结合,自然实现垂直居中,无需额外计算 top: 50% + transform。
该方案兼顾语义清晰性(