在 DIV CSS 佈局的頁面裡,從整體版面到段落文字,居中都是高頻需求。好消息是,用 CSS 實現居中相當簡單。本文分三個層次,帶你搞定各種居中場景。
要讓內容居中,直覺做法是設定父層的 text-align。整個頁面的最外層父級是 <body>,因此可以透過 body 的 CSS 來實現,寫法為 text-align:center;:
body{text-align:center;}
但這樣往往會出問題:如果你沒有設定佈局的寬度(width),一旦最外層設定了 float 屬性,佈局就會往 float 的方向偏移。解法是:除了 body 居中之外,還要為佈局物件本身設定居中並定義寬度。假設網頁寬度為 700px,最外層 class 名為 "weicheng",則寫成:
.weicheng{margin:0 auto; width:700px;}
其中 margin:0 auto; 的意思是上下間距為 0、左右自動平均分配,如此一來,即便在 Firefox 等非 IE 瀏覽器上,也能靠這一句實現佈局居中(寫成 margin:5px auto; 效果相同)。完整範例如下,可複製另存為 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=gb2312" />
<title>CSS div 佈局居中範例</title>
<style type="text/css">
<!--
body{ text-align:center; }
.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(https://www.poluoluo.com/img/css-logo.gif) no-repeat center;}
這段程式碼的意思是:讓 css-logo.gif 不重複(no-repeat)並居中(center)。此處的 center 是左右居中,垂直方向無需特別設定,會自動居中。
左右居中很簡單,直接用 text-align:center; 即可。但垂直居中怎麼辦?若要在高度 120px 的容器內垂直居中:圖片用 vertical-align:middle;,文字則靠設定行高來實現,把 line-height 設為與容器同高(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=gb2312" />
<title>CSS div 完整居中範例</title>
<style type="text/css">
<!--
body{ text-align:center; margin:0 auto; background: url(https://www.poluoluo.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">完整居中範例,外層 1px 邊框 <img src="https://www.poluoluo.com/img/css-logo.gif" alt="圖片內容居中" /></div>
</body>
</html>