大家在制作网页的过程中有时会遇到div嵌套引起的margin-top不起作用,对内部的div设置margin-top时,内部对于外部的div并没有产生一个margin值,而是外部的div相对于上面的div产生了一个margin值,为什么会出现这种情况??
这是因为嵌套div中margin-top出现转移,在部分浏览器中,两个嵌套的div,如果外层父元素div的padding值为0,那么内层div的margin-top,margin-bottom值都会转移到父元素也就是外层div身上。
<head> <title></title> <style type="text/css"> * { padding: 0; margin: 0; } .div1 { height: 500px; width: 100%; background: #ccc; } .div2 { height: 100px; width: 100px; background: red; margin-top: 100px; } </style> </head> <body> <div class="div1"> <div class="div2"></div> </div> </body>
由代码可看出,div1嵌套div2,对div2设置margin-top是100px;
解决办法:
1. 给父元素div1设置一个padding值
.div1{ height: 500px; width: 100%; background: #ccc; padding-top: 1px; }
2. 给父元素div1设置一个overflow:hidden;在不加overflow:Hidden;的时候,margin-top:这个属性是认不到边的,也就是失效。但是ie浏览器解决了这个问题,火狐、谷歌之类的就会出现失效,所以这是个标准问题,也是个兼容问题。
.div1{ height: 500px; width: 100%; background: #ccc; overflow: hidden; }