你对CSS清除浮动的方法是否了解,这里和大家分享一下,在进行浮动布局时,大多数人都深知,在必要的地方进行浮动清理:<divstyle="clear:both;"></div>。
CSS清除浮动的另一种别致的方法
在进行浮动布局时,大多数人都深知,在必要的地方进行浮动清理:<divstyle="clear:both;"></div>。
例如:
ExampleSourceCode
<divstyledivstyle="background:#666;"><!--floatcontainer-->
<divstyledivstyle="float:left;width:30%;height:40px;background:#EEE;">
SomeContent</div>
</div>
- 1.
- 2.
- 3.
- 4.
- 5.
◆此时预览此代码,我们会发现最外层的父元素floatcontainer,并没有显示。这是因为子元素因进行了浮动,而脱离了文档流,导致父元素的height为零。
若将代码修改为:
ExampleSourceCode
<divstyledivstyle="background:#666;"><!--floatcontainer-->
<divstyledivstyle="float:left;width:30%;
height:40px;background:#EEE;">SomeContent</div>
<divstyledivstyle="clear:both"></div>
</div>
- 1.
- 2.
- 3.
- 4.
- 5.
◆注意,多了一段清理浮动的代码。这是一种好的CSS代码习惯,但是这种方法增加了无用的元素。这里有一种更好的方法,将HTML代码修改为:
ExampleSourceCode
<divclassdivclass="clearfix"style="background:#666;"><!--floatcontainer-->
<divstyledivstyle="float:left;width:30%;
height:40px;background:#EEE;">SomeContent</div>
</div>
- 1.
- 2.
- 3.
- 4.
◆定义CSS类,进行“浮动清理”的控制:
ExampleSourceCode
.clearfix:after{}{
content:".";
clear:both;
height:0;
visibility:hidden;
display:block;
}
/*这是对Firefox进行的处理,因为Firefox支持生成元素,
而IE所有版本都不支持生成元素*/
.clearfix{}{
display:inline-block;
}
/*这是对Mac上的IE浏览器进行的处理*/
/**//*HidesfromIE-mac\*/
*html.clearfix{}{height:1%;}
/*这是对win上的IE浏览器进行的处理*/
.clearfix{}{display:block;}
/*这是对display:inline-block;进行的修改,重置为区块元素*/
/**//*EndhidefromIE-mac*/
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
此时,预览以上代码(删去这种注释),会发现即使子元素进行了浮动,父元素floatcontainer仍然会将其包围,进行高度自适应。
代码参考:http://www.positioniseverything.net/easyclearing.html
clear元素的margin-top被重置为零
【编辑推荐】