清理浮动的六种方法(终结版)

        这几天研究清理浮动的方法研究得我头都大了,这玩意儿发展了很多年,所以有很多种方法适用在不同的场景,我总结了一共六种方法,按照推荐顺序列在这里,所谓的推荐顺序也只是一般情况,最终还是要根据你的需求而定,比如说前面推荐的两种方法在我的项目中就不能用。

        各种方法的优缺点我就不一一赘述了,如果你不想研究的话就一个个套,如果你想深入了解的话就只需要仔细研究一下本文末尾列出来的三篇文章就足够了,其他的都可以不用看。

 

方法一: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;">

 

参考文章:

清理浮动的那些事儿(1)——6种清理浮动的方法

Force Element To Self-Clear its Children

A new micro clearfix hack

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值