DIV經常使用的居中方法

一.DIV經常使用的居中方法:css

①利用相對定位設置div外邊距自動調整達到居中效果(ps:若是IE瀏覽器無效果還要在Body裏面加上''text-align:center''這個屬性,或是外面再加一層DIV,設置屬性''text-align:center''),固然居中也有另外一種寫法:margin-left:auto;margin-right:auto             最重要的是div必須設置width屬性html

1 <body>
2   <div style="width:500px;margin:0 auto">
3        .......
4   </div>
5 </body>

 

②利用left和margin-left兩個屬性,先將div塊設置爲margin-left:50%(這表示這個div塊的最左邊那條邊在中間),而後left屬性值爲div塊寬度的負一半瀏覽器

符號表示div向左邊移動寬度的一半。補充說明一下:直接在css中設置left生效的前提是必須設置父容器position:absolute或relativeide

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>無標題文檔</title>
 6 <style>
 7     #myDiv_1{
 8         width:300px;
 9         height:200px;
10         background-color:#F00;    
11         
12         margin-left:50%;
13         position:absolute;
14         left:-150px;
15     }
16 </style>
17 </head>
18 
19 <body>
20     <div id="myDiv_1"></div>
21 </body>
22 </html>
View Code
相關文章
相關標籤/搜索