4.CSS中float导致的高度坍塌问题及解决方法
高度坍塌:浮动元素布局导致的问题
高度坍塌的根源:浮动盒子脱离了常规流,因此常规流盒子进行高度计算时,不会考虑浮动盒子的高度。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container{ padding:30px; background-color:blue; } .sub{ height:100px; width:100px; margin:10px; float:left; background-color: red; } </style> </head> <body> <div class="container"> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> </div> </body> </html>
index.html
效果展示:
.container的div元素没有将10个.sub的div元素包裹。
解决方法:
清除浮动,涉及CSS属性:clear
clear:默认值为none,不清除浮动
clear:both,清除左右浮动,该元素必须出现在所有浮动盒子的下方
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container { padding: 30px; background-color: blue; } .sub { height: 100px; width: 100px; margin: 10px; float: left; background-color: red; } .clearfix::after { content: ""; display: block; clear: both; } </style> </head> <body> <div class="container clearfix"> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> </div> </body> </html>
index.html
效果展示:
赞 (0)