<!DOCTYPE HTML>
<meta charset="UTF-8">
<head>
<title>
理解关于清除浮动的几种情况
</title>
<style type="text/css">
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
</style>
</head>
<body>
<!--如果有一个DIV作为外部容器,内部的DIV如果设置了float样式,-->
<!--则外部的容器DIV因为内部没有clear,导致不能被撑开-->
<div style="border:2px solid red; position: absolute; " >
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">CSSBBS</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
</div>
<!--
原因:因为内部的DIV因为float:left之后,就丧失了clear:both和display:block的样式,
所以外部的DIV不会被撑开
-->
//解决1:
在父容器里追加一个<div style="clear:both"></div>
在最后增加clear
增加无意义标签,不建议用
//解决2:
在父容器上加入clearfix
这个clearfix的CSS应用了after这个伪对象,
它将在利用 clearfix的元素的结尾添加content中的内容。在这里添加了一个句号".",
并且把它的display设置成block;高度设为0;clear设为both;visibility设为潜藏 。
这样就达到 了撑开容器的目标啦
* html .clearfix {height: 1%;}
因为转义字符"\",Mac IE涉猎器会漠视 掉这段Hack,但Windows IE不会,它会利用 * html .clearfix {height: 1%;} 来达到 撑开DIV容器的目标.
.clearfix { *zoom:1;} <----这是针对于IE6的,因为IE6不支持:after伪类,这个神奇的zoom:1让IE6的元素可以清除浮动来包裹内部元素。具体意思的话,和height:1%效果也是一样。
/* clear */
.clearfix:after {content:".";display:block;height:0;clear:both;visibility:hidden;}
.clearfix {zoom:1;display: inline-block;_height:1px;}
//解决3:
给父容器加heigh
//解决4:
给父容器也浮动float:left
此时子元素充满父容器
//解决5:
给父容器overflow: hidden;
//解决5:
给父容器处于绝对定位 position: absolute;
</body>
</html>
理解关于清除浮动的几种情况
最新推荐文章于 2025-08-14 19:06:19 发布