問題
在兩個盒子嵌套時,內部的盒子設置的margin-X會加到外邊的盒子上,導致內部的盒子margin-X設置失敗。。。
解決方案
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>
文章摘自:https://www.cnblogs.com/reyinever/p/10629982.html