本文向大家描述一下CSS清除浮动的方法,清除浮动是必须要做的,而且随时性地对父级元素清除浮动的做法也被认为是书写CSS的良好习惯之一,相信本文介绍一定会让你有所收获。
DIV CSS经验:三种实用CSS清除浮动的方法
前言
用DIV CSS网页布局,经常性地会使用到float,很多邪门的事儿都有可能是浮动在作怪,关于清除浮动,在52CSS.com上有过很多介绍。清除浮动是必须要做的,而且随时性地对父级元素清除浮动的做法也被认为是书写CSS的良好习惯之一。
CSS清除浮动的另一种别致的方法
http://www.52css.com/article.asp?id=915
CSS经验分享:清除浮动及闭合浮动元素方法的总结
http://www.52css.com/article.asp?id=968
下面看今天的教程,此为未清除浮动源代码,运行代码无法查看到父级元素浅黄色背景。
ExampleSourceCode
<styletypestyletype=”text/css”>
*{margin:0;padding:0;}
body{font:36pxbold;color:#F00;text-align:center;}
#layout{background:#FF9;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
style>
<dividdivid=”layout”>
<dividdivid=”left”>Leftdiv>
<dividdivid=”right”>Rightdiv>
div>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
未清除浮动前如图所示:
一、使用空标签清除浮动
我用了很久的一种方法,空标签可以是div标签,也可以是P标签。我习惯用
,够简短,也有很多人用
,只是需要另外为其清除边框,但理论上可以是任何标签。这种方式是在需要清除浮动的父级元素内部的所有浮动元素后添加这样一个标签清楚浮动,并为其定义CSS代码:clear:both。此方法的弊端在于增加了无意义的结构元素。
ExampleSourceCode
<styletypestyletype=”text/css”>
*{margin:0;padding:0;}
body{font:36pxbold;color:#F00;text-align:center;}
#layout{background:#FF9;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
.clr{clear:both;}
–>
style>
<dividdivid=”layout”>
<dividdivid=”left”>Leftdiv>
<dividdivid=”right”>Rightdiv>
<pclasspclass=”clr”>
div>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
#p#二、使用overflow属性
此方法有效地解决了通过空标签元素清除浮动而不得不增加无意代码的弊端。使用该方法是只需在需要清除浮动的元素中定义CSS属性:overflow:auto,即可!”zoom:1″用于兼容IE6。
ExampleSourceCode
<styletypestyletype=”text/css”>
*{margin:0;padding:0;}
body{font:36pxbold;color:#F00;text-align:center;}
#layout{background:#FF9;overflow:auto;zoom:1;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
style>
<dividdivid=”layout”>
<dividdivid=”left”>Leftdiv>
<dividdivid=”right”>Rightdiv>
div>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
三、使用after伪对象清楚浮动
该方法只适用于非IE浏览器。具体写法可参照以下示例。
使用中需注意以下几点。
一、该方法中必须为需要清除浮动元素的伪对象中设置height:0,否则该元素会比实际高出若干像素;
二、content属性是必须的,但其值可以为空,蓝色理想讨论该方法的时候content属性的值设为”.”,但我发现为空亦是可以的。
ExampleSourceCode
<styletypestyletype=”text/css”>
*{margin:0;padding:0;}
body{font:36pxbold;color:#F00;text-align:center;}
#layout{background:#FF9;}
#layout:after{display:block;clear:both;content:”";visibility:hidden;height:0;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
style>
<dividdivid=”layout”>
<dividdivid=”left”>Leftdiv>
<dividdivid=”right”>Rightdiv>
div>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
清楚浮动后如图所示:
此三种方法各有利弊,使用时应择优选择,比较之下第二种方法更为可取。
【编辑推荐】