主要的樣式定義如下:
body { text-align: center; }
#center { margin-right: auto; margin-left: auto; }
說明:首先在父元素定義 text-align: center,意思是讓父元素內的內容居中;對 IE 來說這樣就足夠了,但 Mozilla 系瀏覽器不會生效。解法是在子元素上再加上 margin-right: auto 與 margin-left: auto。
另外要提醒的是,如果你想用這個方法讓整個頁面居中,建議不要全部塞進一個外層容器裡,而是拆成多個區塊,在每個區塊上各自定義左右 margin 為 auto。
用背景圖的方式最省事。舉例:
body { background: url(https://img.sj33.cn/uploads/allimg/200701/20070103022032199.gif) #FFF no-repeat center; }
關鍵就在最後那個 center,它決定圖片的位置。也可以寫成 top left(左上角)或 bottom right,甚至直接用數值,例如 "50 30"。
文字沒辦法用背景圖那招,可以改用「增加行高」的變通做法。完整程式碼:
<style>
body { text-align: center; }
#center {
margin-right: auto;
margin-left: auto;
height: 200px;
background: #F00;
width: 400px;
vertical-align: middle;
line-height: 200px;
}
</style>
<div id="center">test content</div>
說明:vertical-align: middle 表示行內垂直居中,我們把行高增加到與整個容器等高(line-height: 200px),再放入文字,視覺上就垂直居中了。這個技巧的前提是文字維持單行、不換行。