居中是 CSS 布局中最常被問到的需求之一,無論是整個 DIV、圖片還是文字,都有對應的做法。本文逐一破解。
body { text-align: center; }
#center { margin-right: auto; margin-left: auto; }
父層設 text-align:center 讓內容居中,IE 這樣就足夠;但在 Firefox 中還需在子元素加上 margin-right:auto; margin-left:auto; 才能生效。若想讓整個頁面居中,建議拆成多個 div,各自定義左右 auto 邊距即可。
用背景的方式最簡單:
body { background: url(logo.gif) #FFF no-repeat center; }
關鍵是最後的 center,它定義圖片位置;也可寫成 top left、bottom right 或直接給數值。
文字無法用背景法,可用「增加行高」的變通做法:
#center{
margin-right:auto; margin-left:auto;
height:200px; width:400px;
background:#F00;
vertical-align:middle;
line-height:200px;
}
把行高 line-height 設得與整個 DIV 同高,再插入文字,就能讓文字垂直居中。