讓 div 水平居中看似簡單,實則暗藏跨瀏覽器兼容性陷阱。本文揭秘為何 margin: 0 auto 在 Firefox 生效卻在 IE 失效,並提供終極解決方案。
許多開發者發現:設定 margin-left: auto; margin-right: auto; 後,Firefox 完美居中,IE 卻置若罔聞。根因在於頁面缺少 <!DOCTYPE> 聲明,導致 IE 以「怪異模式」渲染,不識別 auto 外邊距計算。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
或使用 HTML5 簡潔聲明(推薦):
<!DOCTYPE html>
<style>
body { text-align: center; } /* IE5/怪異模式兼容 */
#container {
width: 960px; /* 必須設定寬度 */
margin: 0 auto; /* 標準瀏覽器居中核心 */
text-align: left; /* 重置內容對齊 */
}
</style>
<body>
<div id="container">頁面主內容區塊</div>
</body>
若頁面結構複雜,需多層容器居中,每層均需設定 margin: 0 auto:
<div class="wrapper">
<div class="header"></div>
<div class="content"></div>
<div class="footer"></div>
</div>
.wrapper, .header, .content, .footer {
width: 1200px;
margin: 0 auto;
}
.vertical-center {
height: 100px;
line-height: 100px; /* 行高等於容器高度 */
vertical-align: middle;
}
.flex-center {
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
height: 300px;
}
.absolute-center {
position: relative;
}
.absolute-center > * {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<!DOCTYPE html>text-align: center(IE5/怪異模式備援)width 或 max-widthmargin: 0 autotext-align: left 重置內容對齊掌握 DTD 與盒模型渲染機制的關係,是解決歷史瀏覽器佈局兼容性問題的關鍵鑰匙。