清除浮动
方法一:给父元素增加height属性
<style> #app { width: 1000px; height: 500px; background-color: red; } #child1 { width: 300px; height: 300px; background-color: blue; float: left; } #child2 { width: 300px; height: 300px; background-color: green; float: left; } .clear { clear: both; } </style> <body> <div id="app"> <div id="child1"></div> <div id="child2"></div> </div> </body>
![](https://img2020.cnblogs.com/blog/2476357/202110/2476357-20211008141642084-635475751.png)
方法二:给父元素添加overflow:hidden属性,注意此属性对效果的影响
<style> #app { width: 1000px; background-color: red; overflow: hidden; } #child1 { width: 300px; height: 300px; background-color: blue; float: left; } #child2 { width: 300px; height: 300px; background-color: green; float: left; } .clear { clear: both; } </style> <body> <div id="app"> <div id="child1"></div> <div id="child2"></div> </div> </body>
方法三:浮动元素后面增加一个元素,设置clear:both属性
<style> #app { width: 1000px; background-color: red; overflow: hidden; } #child1 { width: 300px; height: 300px; background-color: blue; float: left; } #child2 { width: 300px; height: 300px; background-color: green; float: left; } .clear { clear: both; } </style> <body> <div id="app"> <div id="child1"></div> <div id="child2"></div> <div class="clear"></div> </div> </body>
方法四:使用after伪类清浮动
#app { width: 1000px; background-color: red; } #child1 { width: 300px; height: 300px; background-color: blue; float: left; } #child2 { width: 300px; height: 300px; background-color: green; float: left; } .clearfix:after { content: ' '; display: block; height: 0px; clear: both; visibility: hidden; } .clearfix { zoom: 1; /* ie6-ie7执行,其他浏览器不执行 */ } </style> <body> <div id="app" class="clearfix"> <div id="child1"></div> <div id="child2"></div> </div> </body>
方法五:使用after和before双伪类
<style> #app { width: 1000px; background-color: red; } #child1 { width: 300px; height: 300px; background-color: blue; float: left; } #child2 { width: 300px; height: 300px; background-color: green; float: left; } .clearfix:after, .clearfix:before { content: ' '; display: table; } .clearfix:after { clear: both; } .clearfix { zoom: 1; /* ie6-ie7执行,其他浏览器不执行 */ } </style> <body> <div id="app" class="clearfix"> <div id="child1"></div> <div id="child2"></div> </div> </body>