按照CSS规范,浮动元素(floats)会被移出文档流,不会影响到块状盒子的布局而只会影响内联盒子(通常是文本)的排列。因此当其高度超出包含容器时,一般父容器不会自动伸长以闭合浮动元素。但是有时我们却需要这种自动闭合行为,具体如何处理呢?
在进行浮动布局时,大多数人都深知,在必要的地方进行浮动清理:
,例如: <div style="background:#666;"> <!-- float container --> <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div> </div>此时预览此代码,我们会发现最外层的父元素float container,并没有显示。这是因为子元素因进行了浮动,而脱离了文档流,导致父元素的height为零,若将代码修改为:
<div style="background:#666;"> <!-- float container --> <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div> <div style="clear:both"></div>注意,多了一段清理浮动的代码。这是一种好的CSS代码习惯,但是这种方法增加了无语义的元素。这里有一种更好的方法,将HTML代码修改为:
<div class="clearfix" style="background:#666;"> <!-- float container --> <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>定义CSS类,进行“浮动清理”的控制:
/* 利用生成内容清理浮动 for IE8(标准模式) 和 非IE浏览器 */ .clearfix:after { content: "."; clear: both; height: 0; visibility: hidden; display: block; } /* 激发IE中的hasLayout属性 for IE8(Quirks)模式和IE6\7浏览器*/ .clearfix{ *zoom:1; } /** * 1、'*' hack在IE6\7和IE8 Quirks模式下能够识别,而IE8标准模式下木能识别 * 2、zoom 来激发IE中的hasLayout属性 * 3、设置了{zoom:xx}的元素在IE8的兼容模式或IE8之前的浏览器中其hasLayout为true, * 但在IE8的标准模式下则不会触发hasLayout。 */ 以下是原方法: /* 这是对Firefox进行的处理,因为Firefox支持生成元素,而IE所有版本都不支持生成元素 */ .clearfix:after { content: "."; clear: both; height: 0; visibility: hidden; display: block; } /* 这是对 Mac 上的IE浏览器进行的处理 */ .clearfix { display: inline-block; } /* Hides from IE-mac \*/ * html .clearfix {height: 1%;} /* 这是对 win 上的IE浏览器进行的处理 */ .clearfix {display: block;} /* 这是对display: inline-block;进行的修改,重置为区块元素*/ /* End hide from IE-mac */此时,预览以上代码会发现即使子元素进行了浮动,父元素float container仍然会将其包围,进行高度自适应。