在两个盒子嵌套时,内部的盒子设置的margin-top会加到外边的盒子上,导致内部的盒子margin-top设置失败,解决方法如下:
(1)外部盒子设置一个边框
(2)外部盒子设置overflow:hidden
(3)使用伪元素类:
.clearfix:before{
content:””;
display:table;
}
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>margin-top塌陷</title> <style type="text/css"> .clearfix:before{ content:""; display:table; } /* 第三种解决塌陷的方法,相当于第一种加了边框 第三种方法是最常用的方法 */ .con{ width: 300px; height: 300px; background-color: gold; /*border:1px solid black; /* 第一种解决塌陷的方法 */ /*overflow:hidden; /* 第二种解决塌陷的方法 *!*/ } .box{ width: 200px; height: 100px; background-color: green; margin-top: 100px; } </style> </head> <body> <div class="con clearfix"> <div class="box"></div> </div> </body> </html>
页面显示效果: