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