.parent { text-align: center; }
.child { display: inline-block; }
優點:簡單、相容 IE8+。缺點:需處理 inline-block 間隙(font-size:0 或負 letter-spacing)。
.child { width: 600px; margin: 0 auto; }
優點:標準、相容所有瀏覽器。缺點:需固定寬度。
.parent { position: relative; }
.child { position: absolute; left: 50%; transform: translateX(-50%); }
優點:不需知寬度、支援動畫。缺點:需相對定位父層。
.parent { display: flex; justify-content: center; }
優點:語意清晰、支援多欄等分、無副作用。缺點:IE10+ 部分支援(需前綴)。
.parent { display: grid; place-items: center; }
優點:二維置中一行搞定。缺點:IE 不支援。
.parent { height: 100px; line-height: 100px; }
.parent { display: table-cell; vertical-align: middle; height: 200px; }
.child { /* 任意高度 */ }
優點:相容 IE8+。缺點:父層變 table-cell 會影響佈局流。
.parent::before {
content: ''; display: inline-block; height: 100%; vertical-align: middle;
}
.child { display: inline-block; vertical-align: middle; }
.parent { display: flex; align-items: center; }
.parent { display: grid; place-items: center; }
<img src="transparent.gif" style="width:200px;height:150px;background:url(real.jpg) center no-repeat;">
優點:不需知道圖片實際尺寸、相容極佳。缺點:額外 HTTP 請求(可用 Base64 內嵌透明圖)。
| 方法 | 相容性 | 需知尺寸 | 適用場景 |
|---|---|---|---|
| Flexbox | IE10+ | 否 | 現代專案首選 |
| Grid | 現代瀏覽器 | 否 | 二維佈局 |
| table-cell | IE8+ | 父層需高度 | 相容舊專案 |
| absolute + transform | IE9+ | 否 | 彈窗、Modal |
| inline-block + 偽元素 | IE8+ | 否 | 不想改變 display 的情況 |