您的位置:首页 > 其它

clear:both的认知

2011-07-28 16:56 106 查看
先来看两段代码的效果
1、代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title> clear:both </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>
<div style="border:2px solid blue;">
<div style="float:left;width:100px;height:100px;border:2px solid grey;">测试DIV</div>
<div style="clear:both;"></div>
</div>
</body>
</html>
效果如下:



2、代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title> clear:both </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>
<div style="border:2px solid blue;">
<div style="float:left;width:100px;height:100px;border:2px solid grey;">测试DIV</div>
</div>
</body>
</html>
效果如下:



代码段1比代码段2多了
<div style="clear:both;"></div>
可以发现,原来后边的clear:both;其实就是利用清除浮动来把外层的div撑开。在网上又找到另一种解决方案,可以不需要后面那个DIV,代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title> clear:both </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.clearBoth:after{
visibility: hidden;
display: block;
font-size: 0;
content: ".";
clear: both;
height: 0;
}

* html .clearBoth{
zoom: 1;
}
*:first-child + html .clearBoth{
zoom: 1;
}
</style>
</head>

<body>
<div class="clearBoth" style="border:2px solid blue;">
<div style="float:left;width:100px;height:100px;border:2px solid grey;">测试DIV</div>
<!-- <div style="clear:both;"></div> -->
</div>
</body>
</html>

解析:
(1)、首先是利用:after这个伪类来兼容FF、Chrome等支持标准的浏览器。
:after伪类IE不支持,它用来和content属性一起使用设置在对象后的内容,例如
a:after{content:"(link)";}
这个CSS将会让a标签内的文本后边加上link文本文字
(2)、利用“* html”这个只有IE6认识的选择符,设置缩放属性“zoom: 1;”实现兼容IE6。
(3)、利用“*:first-child + html”这个只有IE7认识的选择符,设置缩放属性“zoom: 1;”实现兼容IE7。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: