在CSS规范中,浮动定位不属于正常的页面流(page flow),是独立定位的。所以,只含有浮动元素的父容器,在显示时不考虑子元素的位置,就当它们不存在一样。这就造成了显示出来,父容器好像空容器一样。如下面这个例子:
<div style="border:1px solid blue;">
<div style="float:left;width:45%;height:300px;background-color:yellow;"></div>
<div style="float:right;width:45%;height:300px; background-color:green;"></div>
</div>
如下图:本应包含两个子元素的父元素并没有包含子元素
我们其实想要的是这种结果:
解决方法:
1.添加一个非浮动元素
<div style="border:4px solid blue;">
<div style="float:left;width:45%;height:300px;background-color:yellow;"></div>
<div style="float:right;width:45%;height:300px; background-color:green;"></div>
<div style="clear:both;"></div>
</div>
<div style="float:left; border:4px solid blue;">
<div style="float:left;width:45%;height:300px;background-color:yellow;"></div>
<div style="float:right;width:45%;height:300px; background-color:green;"></div>
</div>
<div style="overflow: hidden; border:4px solid blue;">
<div style="float:left;width:45%;height:300px;background-color:yellow;"></div>
<div style="float:right;width:45%;height:300px; background-color:green;"></div>
</div>
这种方法的缺点主要有二个,一个是IE 6不支持,另一个是一旦子元素的大小超过父容器的大小,就会出显示问题。
4.通过伪元素
/* For modern browsers */
.cf:before,
.cf:after {
content:"";
display:block;
}
.cf:after {
clear:both;
}
/* For IE 6/7 (trigger hasLayout) */
.cf {
zoom:1;
}
其中的"cf"是父容器的class名称,"content:"";"是在父容器的结尾处放一个空白字符,这个空白字符不显示出来,"display: block; clear: both;"是确保这个空白字符是非浮动的独立区块。
IE 6的独有命令"zoom:1;"就行了,这条命令的作用是激活父元素的"hasLayout"属性,让父元素拥有自己的布局。)IE 6会读取这条命令,其他浏览器则会直接忽略它。
ps:
什么是hasLayout
(以下内容摘自CSS Mastery一书的中译本《精通CSS 高级Web标准解决方案》第154页,人民邮电出版社,2007)
IE使用Layout概念来控制元素的尺寸和位置。如果一个元素有Layout,它就有自身的尺寸和位置;如果没有,它的尺寸和位置由最近的拥有布局的祖先元素控制。
在默认情况下,拥有Layout的元素包括:
<html>, <body>
<table>, <tr>, <th>, <td>
<img>
<hr>
<input>, <button>, <select>, <textarea>, <fieldset>, <legend>
<iframe>, <embed>, <object>, <applet>
<marquee>
(注意,<p>和<div>默认不拥有Layout。)
凡是具有以下CSS属性的元素,也会拥有布局:
- position: absolute
- float: left|right
- display: inline-block
- width: any value other than 'auto'
- height: any value other than 'auto'
- zoom: any value other than 'normal' (IE专用属性)
- writing-mode: tb-rl(IE专用属性)
- overflow: hidden|scroll|auto(只对IE 7及以上版本有效)
- overflow-x|-y: hidden|scroll|auto(只对IE 7及以上版本有效)
hasLayout是IE特有的属性,不是CSS属性。可以用Javascript函数hasLayout查看一个元素是否拥有Layout。如果有,这个函数就返回true;否则返回false。hasLayout是一个只读属性,所以无法使用Javascript进行设置。