HTML&CSS基礎-完善clearfix
作者:尹正傑
版權聲明:原創作品,謝絕轉載!否則將追究法律責任。
一.拋出問題
1>.HTML源代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>完善clearfix</title> <style type="text/css"> .box1{ width: 300px; height: 300px; background-color: red; } .box2{ width: 300px; height: 200px; background-color: yellow; /** * 子元素和父元素相鄰的垂直外邊距會發生重疊,子元素的外邊距會傳遞給父元素。 * 使用空的table標簽可以隔離父子元素的外邊距,阻止外邊距的重疊。 */ margin-top: 100px; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
2>.瀏覽器打開以上代碼渲染結果
二.使用空table解決問題
1>.HTML源代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>完善clearfix</title> <style type="text/css"> .box1{ width: 300px; height: 300px; background-color: red; } .box1:before{ content: ""; /*將一個元素設置為表格顯示*/ display: table; } .box2{ width: 300px; height: 200px; background-color: yellow; /** * 子元素和父元素相鄰的垂直外邊距會發生重疊,子元素的外邊距會傳遞給父元素。 * 使用空的table標簽可以隔離父子元素的外邊距,阻止外邊距的重疊。 */ margin-top: 100px; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
2>.瀏覽器打開以上代碼渲染結果
三.完善clearfix的最終版本
1>.HTML源代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>完善clearfix</title> <style type="text/css"> .box1{ width: 300px; height: 300px; background-color: red; } .box2{ width: 300px; height: 200px; background-color: yellow; /** * 子元素和父元素相鄰的垂直外邊距會發生重疊,子元素的外邊距會傳遞給父元素。 * 使用空的table標簽可以隔離父子元素的外邊距,阻止外邊距的重疊。 */ margin-top: 100px; } .box3{ border: 10px blue solid; } .box4{ width: 100px; height: 100px; background-color: deeppink; float: left; } /** * 解決父子元素的外邊距重疊 * * .box1:before{ * content: ""; * 將一個元素設置為表格顯示 * display: table; * } /** * 解決父元素高度塌陷 * * .clearfix:after{ * content: ""; * display: block; * display: table; * clear: both; * } * / /** * 經過修改后的clearfix是一個多功能的,既可以解決高度塌陷,又可以確保父元素和子元素的垂直外邊距不會重疊 */ .clearfix:after, .clearfix:before{ content: ""; display: table; clear: both; } /*兼容IE6*/ .clearfix{ zoom: 1; } </style> </head> <body> <div class="box3 clearfix"> <div class="box4"></div> </div> <div class="box1 clearfix"> <div class="box2"></div> </div> </body> </html>
2>.瀏覽器打開以上代碼渲染結果