这几天研究清理浮动的方法研究得我头都大了,这玩意儿发展了很多年,所以有很多种方法适用在不同的场景,我总结了一共六种方法,按照推荐顺序列在这里,所谓的推荐顺序也只是一般情况,最终还是要根据你的需求而定,比如说前面推荐的两种方法在我的项目中就不能用。
各种方法的优缺点我就不一一赘述了,如果你不想研究的话就一个个套,如果你想深入了解的话就只需要仔细研究一下本文末尾列出来的三篇文章就足够了,其他的都可以不用看。
方法一:micro clearfix hack(from Nicolas Gallagher)
/** * For modern browsers * 1. The space content is one way to avoid an Opera bug when the * contenteditable attribute is included anywhere else in the document. * Otherwise it causes space to appear at the top and bottom of elements * that are clearfixed. * 2. The use of `table` rather than `block` is only necessary if using * `:before` to contain the top-margins of child elements. */ .cf:before, .cf:after { content: " "; /* 1 */ display: table; /* 2 */ } .cf:after { clear: both; } /** * For IE 6/7 only * Include this rule to trigger hasLayout and contain floats. */ .cf { *zoom: 1; }
如果不需要支持IE 6/7什么的,还有一个简版:
.clearfix:after { display: block; content: " "; clear: both; }
方法二:clearfix hack
.clearfix:after { visibility: hidden; display: block; content: ""; clear: both; height: 0; }
方法三:父元素的overflow设置成auto或hidden;
方法四:父元素设置display为table;
方法五:父元素也浮动;
方法六:父元素的最后添加一个子元素<div style="clear:both;">
参考文章: