有四種方法可以將 css 中的導航欄居中:使用 flexbox(應用 display: flex 和 justify-content: center)、使用網(wǎng)格布局(應用 display: grid 和 justify-items: center)、使用絕對定位(應用 position: absolute、left 和 right: 50% 以及 transform: translate(-50%, 0)),或者使用 margin 自動居中(應用 margin: 0 auto)。
如何使用 CSS 將導航欄居中
1. 使用 Flexbox
Flexbox 是一個布局模型,允許元素在主軸上排列成一行或一列。要使用 Flexbox 將導航欄居中,請執(zhí)行以下步驟:
在導航欄容器上應用 display: flex;。
在 justify-content 屬性上應用 center 值。
<code class="<a style='color:#f60; text-decoration:underline;' href=" https: target="_blank">css">.nav-container {
display: flex;
justify-content: center;
}</code>
登錄后復制
2. 使用網(wǎng)格布局
網(wǎng)格布局允許將元素排列成表格狀的網(wǎng)格。要使用網(wǎng)格布局將導航欄居中,請執(zhí)行以下步驟:
在導航欄容器上應用 display: grid;。
在 justify-items 屬性上應用 center 值。
<code class="css">.nav-container {
display: grid;
justify-items: center;
}</code>
登錄后復制
3. 使用絕對定位
絕對定位允許元素從其正常流中移除并相對于父容器定位。要使用絕對定位將導航欄居中,請執(zhí)行以下步驟:
在導航欄容器上應用 position: absolute;。
在 left 和 right 屬性上應用 50% 值。
在 transform 屬性上應用 translate(-50%, 0);。
<code class="css">.nav-container {
position: absolute;
left: 50%;
right: 50%;
transform: translate(-50%, 0);
}</code>
登錄后復制
4. 使用 margin 自動居中
margin 屬性允許在元素周圍添加空白空間。要使用 margin 自動居中導航欄,請執(zhí)行以下步驟:
在導航欄容器上應用 margin: 0 auto;。
<code class="css">.nav-container {
margin: 0 auto;
}</code>
登錄后復制






