![5c70ceb2bb79b5e17419c243c74636c7.png](https://img-blog.csdnimg.cn/img_convert/5c70ceb2bb79b5e17419c243c74636c7.png)
一般清除浮动的三种方式
第一种给父元素添加overflow: hidden;
我们都知道overflow:hidden可以溢出隐藏,即当内容元素的高度大于其包含块的高度时,设置该属性即可把内容区域超出来的部分隐藏,使内容区域完全包含在该包含块中。
然而"overflow:hidden"还有另外一个特殊的用途,那就是清除包含块内子元素的浮动。
具体代码如下 代码片.
//css代码 .wrap{width: 1000px;margin: 0 auto;border: 2px solid #909090;overflow: hidden;}.wrap>div{width: 200px;height: 200px;border: 2px solid aquamarine;background: #ccc;}.wrap>div:nth-child(1){float: left;}.wrap>div:nth-child(2){float: right;}.wrap>div:nth-child(3){float: left;}
//html
第一个
第二个
第三个
第二种 使用伪类元素+clear: both实现;
伪类元素after可以在元素内部末尾添加内容,并且不再内容框架中显示,它的作用相当于在元素内部末尾添加一个空标签并使用clear: both清楚浮动。
我自己是一名从事了多年开发的web前端老程序员,目前辞职在做自己的web前端私人定制课程,去年我花了一个月整理了一份最适合2019年学习的web前端学习干货,各种框架都有整理,送给每一位前端小伙伴,想要获取的可以关注我的头条号并在后台私信我:前端,即可免费获取。
[建议] 当元素需要撑起高度以包含内部的浮动元素时,通过对伪类设置 clear 或触发 BFC 的方式进行 clearfix。尽量不使用增加空标签的方式。
解释:
触发 BFC 的方式很多,常见的有:
float 非 none
position 非 static
overflow 非 visible
//css.clearfix:after{content: "200b";/*0宽度的空格*/display: block;height: 0;clear: both;}.wrap{width: 1000px;margin: 0 auto;border: 2px solid #909090;}.wrap>div{width: 200px;height: 200px;border: 2px solid aquamarine;background: #ccc;}.wrap>div:nth-child(1){float: left;}.wrap>div:nth-child(2){float: right;}.wrap>div:nth-child(3){float: left;}
//html
第一个
第二个
第三个
第三种 父元素添加高度;
直接在父元素添加高度
//css.wrap{width: 1000px;margin: 0 auto;border: 2px solid #909090;height:204px;}.wrap>div{width: 200px;height: 200px;border: 2px solid aquamarine;background: #ccc;}.wrap>div:nth-child(1){float: left;}.wrap>div:nth-child(2){float: right;}.wrap>div:nth-child(3){float: left;}
//html
第一个
第二个
第三个
![5929f26de02034af75a059eb2ad35339.png](https://img-blog.csdnimg.cn/img_convert/5929f26de02034af75a059eb2ad35339.png)
原文链接:https://blog.csdn.net/weixin_44965420/article/details/104248643