有四种方法可以将 CSS 中的导航栏居中:使用 Flexbox(应用 display: flex 和 justify-content: center)、使用网格布局(应用 display: grid 和 justify-items: center)、使用绝对定位(应用 position: absolute、left 和 right: 50% 以及 transform: translate(-50%, 0)),或者使用 margin 自动居中(应用 margin: 0 auto)。

如何使用 CSS 将导航栏居中
1. 使用 Flexbox
Flexbox 是一个布局模型,允许元素在主轴上排列成一行或一列。要使用 Flexbox 将导航栏居中,请执行以下步骤:
- 在导航栏容器上应用
display: flex;。 - 在
justify-content属性上应用center值。
.nav-container {
display: flex;
justify-content: center;
}2. 使用网格布局
立即学习“前端免费学习笔记(深入)”;
网格布局允许将元素排列成表格状的网格。要使用网格布局将导航栏居中,请执行以下步骤:
本文档主要讲述的是iOS界面设计尺寸规范;在最新的iOS7的风格中,苹果已经开始慢慢弱化状态栏的存在,将状态栏和导航栏合在了一起,但是再怎么变,尺寸高度也还是没有变的,只不过大家在设计iOS7风格的界面的时候多多注意下。感兴趣的朋友可以过来看看
- 在导航栏容器上应用
display: grid;。 - 在
justify-items属性上应用center值。
.nav-container {
display: grid;
justify-items: center;
}3. 使用绝对定位
绝对定位允许元素从其正常流中移除并相对于父容器定位。要使用绝对定位将导航栏居中,请执行以下步骤:
- 在导航栏容器上应用
position: absolute;。 - 在
left和right属性上应用50%值。 - 在
transform属性上应用translate(-50%, 0);。
.nav-container {
position: absolute;
left: 50%;
right: 50%;
transform: translate(-50%, 0);
}4. 使用 margin 自动居中
margin 属性允许在元素周围添加空白空间。要使用 margin 自动居中导航栏,请执行以下步骤:
- 在导航栏容器上应用
margin: 0 auto;。
.nav-container {
margin: 0 auto;
}









