有你在真好 的个人博客
详解css清除浮动方法
阅读:2176 添加日期:2021/3/27 23:30:26 原文链接:https://www.toutiao.com/item/6204691518818271745/

清除浮动,新手朋友往往不是很明白。如果不清除浮动对float进行闭合,在FF中往往会出错,网上是有很多文章讲过,我们先用一个非常简洁易用实例开始吧!

给需要闭合的DIV(class为clearfix)加上如下的CSS样式即可:

.clearfix:after{content:”.”;display:block;height:0;clear:both;visibility:hidden;}
*html .clearfix{height:1%;}
*+html .clearfix{height:1%;}
.clearfix{display:inline-block;}
.clearfix {display:block;}

不过貌似这样有点麻烦,呵呵,大前端常用的是下面的:

.clear{clear:both;height:0px;overflow:hidden;}

上述两种浮动闭合的办法CSS清除浮动 万能float闭合,但是很多同学都在使用下面的骨灰级解决办法,这里也把他罗列出来:

.clear{clear:both;height:0;overflow:hidden;}

上述办法是在需要清除浮动的地方加个div.clear或者br.clear,我们知道这样能解决基本清浮动问题。

但是这种方法的最大缺陷就是改变了html结构,虽然只是加个div。

最优浮动闭合方案(这是我们推荐的):

.clearfix:after {
content:".";
display:block;
height:0;
clear:both;
visibility:hidden
}
.clearfix {
*+height:1%;
}

用法很简单,在浮动元素的父云素上添加class=”demo clearfix”。

你会发现这个办法也有个弊端,但的确是小问题。改变css写法就ok了:

.demo:after,.demo2:after {
content:".";
display:block;
height:0;
clear:both;
visibility:hidden
}
.demo,.demo2 {
*+height:1%;
}

以上写法就避免了改变html结构,直接用css解决了。

很拉轰的浮动闭合办法:

.clearfix {
overflow:auto;
_height:1%;
}

测试了,百试不爽,真的很简单,很给力。喜欢的同学也可以试试这个办法。

另外下方面方法,测试通过:

.clearfix {
overflow:hidden;
_zoom:1;
}

文/丁向明

加我qq/微信交流:6135833,做一个有博客的web前端自媒体人

http://dingxiangming.com

ICP备案号:苏ICP备14035786号-1 苏公网安备 32050502001014号