CSS 如何使DIV層水平居中css
DIV自己沒有定義本身居中的屬性,html
網上不少的方法都是介紹用上級的text-align: center而後嵌套一層DIV來解決問題.express
但是事實上這樣的方法科學嗎?網絡
通過網絡搜索和親自實驗得出如下結論:動畫
正確的也是對頁面構造沒有影響的設置以下:url
對須要水平居中的DIV層添加如下屬性:
spa
margin-left: auto; margin-right: auto;
通過這麼一番設置問題彷佛解決了,在FF中已經居中了,但是在IE中看居然仍是沒有居中!code
問題到底出在哪裏呢?xml
若是沒有在HTML前加上DTD,那麼IE就以HTML而不是XHTML來解釋文檔.htm
因此,問題並不在CSS而在XHTML網頁自己.
須要加上這樣的代碼才能使得上述設置有效果:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
若是您但願更爲嚴格的XHTML 1.0 Strict或者XHTML 1.1請查閱相關文檔.
如何使DIV居中
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type="text/css"> body{ margin: 0px; padding:0px; text-align:center; } .container{ /*position:relative;*/ border:1px red solid; margin:0px auto; text-align: left; width:980px; } .head{ margin:auto; text-align:center; width:300px; border:1px red solid; background:lightblue; } .content{ margin:auto; width:300px; border:1px green dotted; background:goldenrod; } </style> <title>3</title> </head> <body> <div class="container"> <div class="head">動畫</div> <div class="content"> 經過不透明度的變化來實現全部匹配元素的淡入效果, 經過不透明度的變化來實現全部匹配元素的淡入效果, 經過不透明度的變化來實現全部匹配元素的淡入效果, </div> </div> </body> </html>
主要的樣式定義以下:
body {TEXT-ALIGN: center;}
#center { MARGIN-RIGHT: auto; MARGIN-LEFT: auto; }
說明:
首先在父級元素定義TEXT-ALIGN: center;這個的意思就是在父級元素內的內容居中;對於IE這樣設定就已經能夠了。但在mozilla中不能居中。解決辦法就是在子元素定義時候設定時再加上"margin:auto;"或「margin-left: auto;margin-right: auto; 」
須要說明的是,若是你想用這個方法使整個頁面要居中,建議不要套在一個DIV裏,你能夠依次拆出多個div,只
要在每一個拆出的div裏定義MARGIN-RIGHT: auto;MARGIN-LEFT: auto; 就能夠了。
如何使圖片在DIV 中垂直居中,用背景的方法。舉例:
body{BACKGROUND: url(http://www.w3cn.org/style/001/logo_w3cn_194x79.gif) #FFF no-repeat center;}
關鍵就是最後的center,這個參數定義圖片的位置。還能夠寫成「top left」(左上角)或者"bottom right"等,也能夠直接寫數值"50 30"
如何使文本在DIV中垂直居中
若是是文字,便不能用背景方法,能夠用增高行距的辦法變通實現垂直居中,完整代碼以下:
<html> <head> <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> </head> <body > <div id="center"><p>test content</p></div> </body> </html>
vertical-align:middle;表示行內垂直居中,咱們將行距增長到和整個DIV同樣高line-height:200px;而後插入文字,就垂直居中了。
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:50;height:50"> </div>