DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS特效代碼
CSS 水平與垂直居中的多種實現方法
編輯:CSS特效代碼     

一、水平居中

DIV 等標籤本身沒有居中屬性,網路上常見做法是透過上層 text-align: center 再嵌套一層 DIV,但這方法有時無效,對布局也不夠科學。正確寫法如下(不影響頁面結構):

div { margin-left: auto; margin-right: auto; }

意思是讓 div 自動調整左右 margin 間距以達水平居中,也可簡寫為 div { margin: 0px auto; };但要注意,若之後調整 margin-top 或 margin-bottom,就會失去水平居中效果。此外,若 div 未指定寬度,這種寫法也無效,解法是為它指定 width(如 width:50%)。同時頁面的 DOCTYPE 必須正確宣告。此寫法也適用於 img 等盒狀標籤。若 IE 與 Firefox 顯示不一致,建議 text-align:center 與 margin 兩者一起設定:

#layout { text-align: center; }
#center { margin-right: auto; margin-left: auto; }

先在父元素設 text-align: center(IE 即可生效),再在子元素補上 margin-right/left: auto(解決 Firefox 無法居中的問題)。若整個頁面要居中,建議拆成多個 div,各自定義 margin auto 即可。

二、垂直居中

1. 讓圖片在 DIV 中垂直居中:可用背景圖片方式,關鍵在於 center 屬性:

body { background: url("sample.gif") #FFF no-repeat center; }

也可把 center 換成 top、left 或直接寫數字來調整位置。

2. 讓文字在 DIV 中垂直居中:可用增大行距的方式變通實現:

#center { margin-right: auto; margin-left: auto; height: 200px; vertical-align: middle; line-height: 200px; }
<div id="center"><p>test content</p></div>

把行距增加到與整個 DIV 同高(line-height:200px),文字自然就垂直居中了。

3. 透過 CSS+DIV 控制元素垂直居中(全局與區域居中):

<style type="text/css" media="screen">
body { text-align: center; }
#a { width: 200px; height: 400px; background: #000; }
#b { margin-top: expression((a.clientHeight-50)/2); width: 50px; height: 50px; background: #FFF; }
#c { position: absolute; left: expression((body.clientWidth-50)/2); top: expression((body.clientHeight-50)/2); width: 50px; height: 50px; background: #F00; }
</style>
<div id="a"><div id="b"></div></div>
<div id="c"></div>

另一種居中寫法:

<div style="background:blue; position:absolute; left:expression((body.clientWidth-50)/2); top:expression((body.clientHeight-50)/2); width:50px; height:50px;"></div>

水平垂直居中範例:

#LoginBar { position: absolute; left: 50%; top: 50%; margin-top: -68px; margin-left: -150px; width: 300px; height: 156px; text-align: left; z-index: 1; }
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved