在 DIV+CSS 佈局的頁面裡,從整體版面的置中到文章文字的置中,都是非常重要的細節。以下分三個層次說明如何用 CSS 完成置中。
整個頁面的父級是什麼?我們可以想像頁面內容是被 body 包住的,因此根據「就近父級」原則,只要設定 body 的 CSS 就能處理置中。
內容置中我們熟悉的是 text-align:center;,這個屬性在 IE 下有效;但實測在 Firefox 等瀏覽器下,只設 text-align:center; 是無法讓佈局置中的。因此還需要加上 margin:0 auto;——意思是上下間距為 0,左右為 auto 自動分配,這樣就能實現網頁佈局置中:
body { text-align:center; margin:0 auto; }
但即使這樣也會出問題,因為你還沒設定佈局有多寬。一旦你的最外層容器設定了 float,佈局就會往 float 的方向靠。解法是:除了 body 的置中設定外,還要讓最外層 div 也置中,並明確定義寬度。假設網頁寬度為 700px,最外層 class 為 weicheng,就這樣寫:
.weicheng { margin:0 auto; width:700px; }
完整範例(可直接複製成 HTML 檔開啟預覽):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS div 佈局置中範例</title>
<style type="text/css">
body { text-align:center; margin:0 auto; }
.waicheng {
color:#0066CC;
margin:5px auto;
width:700px;
height:200px;
border:1px solid #000000;
}
</style>
</head>
<body>
<div class="waicheng">
我是 CSS 置中範例。我的外層有一個 1px 的黑色邊框,
寬 700px,高 200px,並設定與頂部內容距離為 5px。
</div>
</body>
</html>
這裡的置中包含左右與上下兩個方向:
body {
background:#FFF url(/images/bg.gif) no-repeat center;
}
其中 no-repeat 讓背景不重複,center 則讓背景左右置中;垂直方向不需另外設定,會自動置中。
左右置中很好辦,直接用 text-align:center; 就能讓文字與圖片內容水平居中。垂直方向則要分開處理:圖片用 vertical-align:middle;,文字則靠設定行高來達成。
以下是在高度 120px 的容器中同時完成背景置中、內容置中的完整範例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS div 完整置中範例</title>
<style type="text/css">
body {
text-align:center;
margin:0 auto;
background:url(https://www.divCSS5.com/img/CSS-logo.gif) no-repeat center;
}
.waicheng {
color:#0066CC;
margin:5px auto;
width:700px;
height:120px;
line-height:120px;
border:1px solid #000000;
}
.waicheng img { vertical-align:middle; }
</style>
</head>
<body>
<div class="waicheng">
我是 CSS 完整置中範例,我的外層有一個 1px 的邊框。
<img src="/images/demo.gif" alt="圖片內容置中" />
</div>
</body>
</html>
關鍵點在於:line-height 要跟容器高度設成相同數值,文字才會在垂直方向真正居中;而圖片則靠 vertical-align:middle 對齊基線。