CSS如何使DIV層水平置中

來源:互聯網
上載者:User
這兩天開始對網誌進行大刀闊斧的頁面更改.
今天碰到個很棘手的問題,div本身沒有定義自己置中的屬性,
網上很多的方法都是介紹用上級的text-align: center然後嵌套一層div來解決問題.
可是事實上這樣的方法科學嗎?
經過網路搜尋和親自實驗得出以下結論:
正確的也是對頁面構造沒有影響的設定如下:
對需要水平置中的div層添加以下屬性:

margin-left: auto;
margin-right: auto;

經過這麼一番設定問題似乎解決了,在ff中已經置中了,可是在ie中看竟然還是沒有置中!
鬱悶了一下午,就是找不出問題所在,還特地比較了網上的文章竟然一模一樣.
問題到底出在哪裡呢?
感謝網友樂天無用幫忙找出了這個邪門問題的原因.
原來是l-blog預設沒有在html前加上dtd,於是ie就以html而不是xhtml來解釋文檔.
問題並不在css而在xhtml網頁本身.
需要加上這樣的代碼才能使得上述設定有效果:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">[/code]

如果您希望更為嚴格的xhtml 1.0 strict或者xhtml 1.1請查閱相關文檔.
以上測試均基於windows xp sp2版ie6和firefox 1.0最終版.

如何使div置中

主要的樣式定義如下:

[code]body {text-align: center;}
#center { margin-right: auto; margin-left: auto; }

 

說明:
首先在父級元素定義text-align: center;這個的意思就是在父級元素內的內容置中;對於ie這樣設定就已經可以了。但在mozilla中不能置中。解決辦法就是在子項目定義時候設定時再加上“margin-right: auto;margin-left: auto; ”
需要說明的是,如果你想用這個方法使整個頁面要置中,建議不要套在一個div裡,你可以依次拆出多個div,只
要在每個拆出的div裡定義margin-right: auto;margin-left: auto; 就可以了。
如何使圖片在div 中垂直置中

用背景的方法。舉例:

body{background: url(http://www.w3cn.org/style/001/logo_w3cn_194x ... nbsp;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>
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.