採用 #container 包裹全頁內容的經典 DIV+CSS 佈局中,body 與 #container 的樣式配合決定了頁面是否完美居中。本文深度解析核心屬性與原理。
body {
margin: 0;
padding: 0;
text-align: center; /* 關鍵:IE5/怪異模式下讓區塊元素居中 */
}
margin: 0; padding: 0;:消除瀏覽器默認邊距,內容貼邊顯示text-align: center;:在 IE5.x 與怪異模式下,此屬性能讓區塊級子元素水平居中(標準模式下僅影響行內內容)#container {
width: 760px; /* 必須:明確寬度,auto 才能計算 */
margin: 0 auto; /* 核心:上下 0,左右 auto 瀏覽器自動分配 */
text-align: left; /* 重置:抵消 body 的 center 遺傳,內容靠左 */
position: relative; /* 關鍵:建立定位上下文,子元素 absolute 定位參考 */
}
| 屬性 | 作用 | 原理 |
|---|---|---|
width |
定義容器寬度 | 無寬度則撐滿父容器,無法居中 |
margin: 0 auto |
水平居中核心 | 瀏覽器自動計算左右外邊距使其相等 |
text-align: center (body) |
IE5/怪異模式兼容 | 舊版 IE 以此屬性控制區塊元素對齊 |
text-align: left (container) |
重置內容對齊 | 避免內容文字、圖片意外居中 |
position: relative |
建立定位上下文 | 子元素 position: absolute 時以此為參考點 |
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>居中佈局示例</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { text-align: center; background: #f0f0f0; }
#container {
width: 1200px;
max-width: 100%; /* 響應式:小屏自適應 */
margin: 0 auto;
text-align: left;
background: #fff;
position: relative;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div id="container">
<header>頁首區域</header>
<main>主內容區域</main>
<footer>頁腳區域</footer>
</div>
</body>
</html>
#container {
width: 100%;
max-width: 1200px; /* 最大寬度限制 */
margin: 0 auto;
padding: 0 20px; /* 移動端邊距緩衝 */
/* 其餘屬性不變 */
}
width 或 max-width<!DOCTYPE html> 導致 IE 怪異模式float 或 position: absolute 干擾margin 合併導致佈局偏移box-sizing: border-box 統一盒模型