div內嵌p,div等塊元素出現的問題

div內嵌p,div等塊元素出現的問題

http://caiceclb.iteye.com/blog/428085css

div內部塊級元素,好比p,div,設置外間距(margin)的話會怎樣。原本還納悶div莫名奇妙的怎麼多出了一些外邊距,甚至設置margin爲0,都不能解決問題。究竟是怎麼回事呢?html

一、chrome

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <title>div嵌套p/div</title>
 5   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 6   <style type="text/css">
 7     body,p,div {margin:0;padding:0;}
 8     #top,#bottom {background:red;}
 9     #bottom{background:green;}
10     p{margin:20px;}
11     #div {margin:30px;}
12     #div {margin:0;}
14   </style>
15 </head>
16 <body>
17   <div id="top">
18     <p>p-tag margin</p>
19   </div>
20   <div id="bottom">
21     <div id="div">div margin</div>
22   </div>
23 </body>
24 </html>

如今 p.margin="20px";FF,chrome,opera,IE6,IE9測試發現div#top並無變大,看底色就知道;但卻多了個margin。測試

那設定#top.margin=0;呢?沒用。ui

而後#div.margin:30px;發現出現同樣的問題。spa

 

怎麼辦?幸好我之前看過怎麼測試修改方面的資料;加border或者overflow,zoom(ie)。code

 

解決方案1,給#top加border測試; border:1px solid #000;htm

  好,正常了,可是邊框有寬度啊,影響效果。那就加個margin:-1px; 測試發現沒效果,高度仍是多了2px。blog

解決方案2:get

overflow:hidden; 測試效果:FF,chrome,opera,ie9都有效果,ie6沒效果;

zoom:1; 測試只有ie6有效果;

二者結合一塊兒使用呢?測試:都有效果。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <title>div嵌套p/div</title>
 5   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 6   <style type="text/css">
 7     body,p,div {margin:0;padding:0;zoom:1;overflow:hidden;}/*border:1px solid #000;margin:-1px;*/
 8     #top,#bottom {background:red; }
 9     #bottom{background:green;}
10     p{margin:20px;}
11     #div {margin:30px;}
12     #div {margin:0;}
13   </style>
14 </head>
15 <body>
16   <div id="top">
17     <p>p-tag margin</p>
18   </div>
19   <div id="bottom">
20     <div id="div">div margin</div>
21   </div>
22 </body>
23 </html>

 

/////////////////////////////////////////////////////////////////////////////////

原理我不清楚,先用着;固然建議不要這麼嵌套着用。

相關文章
相關標籤/搜索