浮动是布局中经常采用的手段,但是浮动带来的高度塌陷却为布局带来麻烦,所以我们经常需要清除浮动,下文记录几种常用的清除浮动手段
高度塌陷:
clear属性
第一种运用clear的方式在需要清浮动的元素下放一个div,并加上clear:both
some text
复制代码
css
.float{ width:300px;height:300px; float:left; background: green; opacity: .5; } p{ background:red; } .clear{ clear:both; }复制代码
第二种方式是用伪元素:before
或:after
some text
复制代码
css
.content:after{ content:''; display:'block'; clear:both; } float{ width:300px;height:300px; float:left; background: green; opacity: .5; } p{ background:red; }复制代码
overflow:hidden
该方法利用了BFC的特性,当元素有以下特性时,触发BFC
html
根元素float
的值不为none
overflow
的值为hidden、auto或scrollposition
的值不为static
或relative
display
的值为table-cell
、table-caption
、或inline-block
html
some text
复制代码
css
.content{ overflow: hidden; } .float{ float:left; width:100px;height:100px; background: green; opacity: .5; } p{ background:red; }复制代码
清除浮动效果图: