場景:`
<div id="macji">
<ul class="macji-skin">
<li>列表一</li>
<li>列表二</li>
<li>列表三</li>
<!-- 動態增減 li 均可居中 -->
</ul>
</div>
<style>
#macji {
position: relative;
width: 100%;
height: 80px;
background-color: #eee;
text-align: center; /* 兜底:無浮動時文字居中 */
overflow: hidden; /* 容納浮動、防溢出 */
}
#macji .macji-skin {
float: left; /* 關鍵:ul 必須浮動,才能讓 left:50% 相對父級定位 */
position: relative;
left: 50%; /* ul 左邊緣移至容器中心 */
/* 無需設寬度,由 li 撐開 */
}
#macji .macji-skin li {
position: relative;
right: 50%; /* li 內容區右移 50% → 視覺中心對齊 */
float: left; /* 關鍵:li 必須浮動並排 */
margin: 10px;
padding: 0 10px;
border: solid 1px #000;
line-height: 60px;
white-space: nowrap; /* 防止內容換行破壞居中 */
}
</style>
| 元素 | 關鍵屬性 | 作用 | 缺一不可? |
|---|---|---|---|
| 父容器 | `position:relative` | 建立定位上下文 | ✅ 是 |
| ul | `float:left` + `position:relative` + `left:50%` | 脫流並左邊緣對齊中心 | ✅ 是 (三者缺一不可) |
| li | `float:left` + `position:relative` + `right:50%` | 並排 + 內容區中心對齊 | ✅ 是 |
| 方案 | 代碼 | 支援度 | 優勢 |
|---|---|---|---|
| Flex (首選) | `ul { display: flex; justify-content: center; }` | IE10+ (舊語法) | 語義正確、無副作用、支援換行/對齊/間距 |
| Inline-block + text-align | `ul { text-align: center; } li { display: inline-block; }` | 全瀏覽器 | 簡單、無浮動副作用、需處理字符間距 |
| Grid | `ul { display: grid; justify-content: center; grid-auto-flow: column; gap: 20px; }` | 現代瀏覽器 | 二維對齊、gap 原生間距、自動換行 |
| Table (極舊兼容) | `ul { display: table; margin: 0 auto; } li { display: table-cell; }` | IE8+ | 語義偏差、單行、難控制間距 |
/* 現代項目:直接用 Flex */
.nav-list {
display: flex;
flex-wrap: wrap; /* 允許換行 */
justify-content: center; /* 主軸居中 */
align-items: center; // 交叉軸居中
gap: 20px; // 統一間距,無需 margin 負值抵消
list-style: none;
padding: 0;
}
總結:Float+Relative 偽居中是 CSS 發展史上的智慧結晶,解決了時代痛點。現代項目請毫不猶豫選擇 Flex/Grid,將精力投入業務創新而非兼容性 Hack。