div内嵌p,div等块元素出现的问题

时间:2023-03-09 05:57:17
div内嵌p,div等块元素出现的问题

div内嵌p,div等块元素出现的问题

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

div内部块级元素,比如p,div,设置外间距(margin)的话会怎样。本来还纳闷div莫名奇妙的怎么多出了一些外边距,甚至设置margin为0,都不能解决问题。到底是怎么回事呢?

1、

 <!DOCTYPE html>
<html>
<head>
<title>div嵌套p/div</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body,p,div {margin:0;padding:0;}
#top,#bottom {background:red;}
#bottom{background:green;}
p{margin:20px;}
#div {margin:30px;}
#div {margin:0;}
</style>
</head>
<body>
<div id="top">
<p>p-tag margin</p>
</div>
<div id="bottom">
<div id="div">div margin</div>
</div>
</body>
</html>

现在 p.margin="20px";FF,chrome,opera,IE6,IE9测试发现div#top并没有变大,看底色就知道;但却多了个margin。

那设定#top.margin=0;呢?没用。

然后#div.margin:30px;发现出现一样的问题。

怎么办?幸亏我以前看过怎么测试修改方面的资料;加border或者overflow,zoom(ie)。

解决方案1,给#top加border测试; border:1px solid #000;

好,正常了,但是边框有宽度啊,影响效果。那就加个margin:-1px; 测试发现没效果,高度还是多了2px。

解决方案2:

overflow:hidden; 测试效果:FF,chrome,opera,ie9都有效果,ie6没效果;

zoom:1; 测试只有ie6有效果;

两者结合一起使用呢?测试:都有效果。

 <!DOCTYPE html>
<html>
<head>
<title>div嵌套p/div</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body,p,div {margin:0;padding:0;zoom:1;overflow:hidden;}/*border:1px solid #000;margin:-1px;*/
#top,#bottom {background:red; }
#bottom{background:green;}
p{margin:20px;}
#div {margin:30px;}
#div {margin:0;}
</style>
</head>
<body>
<div id="top">
<p>p-tag margin</p>
</div>
<div id="bottom">
<div id="div">div margin</div>
</div>
</body>
</html>

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

原理我不清楚,先用着;当然建议不要这么嵌套着用。