先看一段典型的結構:
<div style="width:1000px;margin:0 auto;">
<div style="background-color:red; text-align:left;">區塊1</div>
<div style="background-color:yellow;">區塊2</div>
</div>
理論上外層容器透過 margin:0 auto 應該水平居中,但在 IE9 環境下卻出現了靠左對齊的異常表現。
要解決這個問題,需要區分瀏覽器版本:
IE9 及以上:只要為容器設定 margin:0px auto; 即可讓 DIV 正常居中,這是符合標準的寫法。
IE9 以下:由於舊版 IE 對居中解析存在缺陷,需要多包一層,並借助 text-align 來觸發居中:
<div style="text-align:center">
<div style="margin-left:auto; margin-right:auto;"></div>
</div>
如此一來,內層的子 DIV 便能正確地居中顯示。這本質上是利用父層的 text-align:center 對舊版 IE 進行兼容補償。