<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{margin:0px; padding:0px;} .box1{ width: 300px; height: 300px; background-color: red } .box2{ width: 200px; height: 200px; background-color: yellow; margin-top: 100px; } </style> </head> <body> <div class="box1 "> <div class="box2"></div> </div> </body> </html>
當把子元素margin-top:100 時,其父元素會跟着一樣改變
解決方法
用css解決
.clearfix:before, .clearfix:after{ content: ""; display: table; clear: both; } .clearfix{ zoom: 1; }
形成以下完全代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{margin:0px; padding:0px;} .box1{ width: 300px; height: 300px; background-color: red } .box2{ width: 200px; height: 200px; background-color: yellow; margin-top: 100px; } .clearfix:before, .clearfix:after{ content: ""; display: table; clear: both; } .clearfix{ zoom: 1; } </style> </head> <body> <div class="box1 clearfix"> <div class="box2"></div> </div> </body> </html>
運行后變成