1. 使用额外标签法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .outer{ border: 1px solid black; 210px; } .inner{ 50px; height: 50px; background-color: #005FC3; margin:0 10px; float: left; } .footer{ background-color: #ff4400; 212px; height: 100px; } .clearfix{ clear: both; } </style> </head> <body> <div class="outer"> <div class="inner"></div> <div class="inner"></div> <div class="inner"></div> <div class="clearfix"></div> </div> <div class="footer"></div> </body> </html>
这是早期普遍使用的方法,但是对于有代码洁癖的人来说,解决的不够完美
2. 使用 :after 为元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .outer{ border: 1px solid black; 210px; } .inner{ 50px; height: 50px; background-color: #005FC3; margin:0 10px; float: left; } .footer{ background-color: #ff4400; 212px; height: 100px; } .clearfix:after{ /*最简方式*/ content: ''; display: block; clear: both; } /* 新浪使用方式 .clearfix:after{ content: ''; display: block; clear: both; height: 0; visibility: hidden; } */ .clearfix{ /*兼容 IE*/ zoom: 1; } </style> </head> <body> <div class="outer clearfix"> <div class="inner"></div> <div class="inner"></div> <div class="inner"></div> </div> <div class="footer"></div> </body> </html>
3. 给父元素定高
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .outer { border: 1px solid black; 210px; height: 50px; } .inner { 50px; height: 50px; background-color: #ff4400; margin: 0 10px; float: left; } .footer { background-color: #005FC3; 212px; height: 100px; } </style> </head> <body> <div class="outer"> <div class="inner"></div> <div class="inner"></div> <div class="inner"></div> </div> <div class="footer"></div> </body> </html>
4. 利用 overflow:hidden 属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .outer{ border: 1px solid black; 210px; overflow: hidden; zoom: 1;/*兼容 IE*/ } .inner{ 50px; height: 50px; background-color: #005FC3; margin:0 10px; float: left; } .footer{ background-color: #ff4400; 212px; height: 100px; } </style> </head> <body> <div class="outer"> <div class="inner"></div> <div class="inner"></div> <div class="inner"></div> </div> <div class="footer"></div> </body> </html>