CSS:浮动清理,不使用 clear:both标签

王朝html/css/js·作者佚名  2008-08-27
窄屏简体版  字體: |||超大  

在进行浮动布局时,大多数人都深知,在必要的地方进行浮动清理:<div style="clear:both;"></div>。

例如:

<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>

</div>

注意,多了一段清理浮动的代码。这是一种好的CSS代码习惯,但是这种方法增加了无用的元素。这里有一种更好的方法,将HTML代码修改为:

<div class="clearfix" style="background:#666;"> <!-- float container -->

<div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>

</div>

定义CSS类,进行“浮动清理”的控制:

.clearfix:after {}{

content: ".";

clear: both;

height: 0;

visibility: hidden;

display: block;

} /* 这是对Firefox进行的处理,因为Firefox支持生成元素,而IE所有版本都不支持生成元素 */

.clearfix {}{

display: inline-block;

} /* 这是对 Mac 上的IE浏览器进行的处理 */

/**//* Hides from IE-mac \*/

* html .clearfix {}{height: 1%;} /* 这是对 win 上的IE浏览器进行的处理 */

.clearfix {}{display: block;} /* 这是对display: inline-block;进行的修改,重置为区块元素*/

/**//* End hide from IE-mac */

此时,预览以上代码( 删去这种注释 ),会发现即使子元素进行了浮动,父元素float container仍然会将其包围,进行高度自适应。

代码参考:http://www.positioniseverything.net/easyclearing.html

clear元素的margin-top被重置为零

当你使用clear(left & both & right)清理一个浮动元素时,该元素的margin-top会被重置为0。所以为了创建浮动列,并使用footer进行浮动清理时,必须对浮动列(sidebar && content)都指定margin-bottom,最好margin-bottom相同。(Firefox会将margin-top重置0,而IE不重置footer的margin-top)。

例如:

分别在Firefox和IE中运行一下代码,仔细读者会发现页脚(footer)的margin-top在火狐中并没有显示,而在IE中却出现了10像素的上边距。 HTML代码

<body>

<div id="wrapper">

<div id="masthead">

masthead content goes here

</div>

<div id="sidebar">

sidebar content goes here

</div>

<div id="content">

main content goes here

<br/>

main content goes here

</div>

<div id="footer">

footer

</div>

</div>

</body>CSS代码 body {}{

margin:0; padding:0;

background-color:#FFFFCC;

}

#wrapper {}{

width:800px;

margin:0 auto;

}

/**//*Masthead*/

#masthead {}{

padding:10px;

background:#FFCC33;

margin-bottom:10px;

}

/**//*Content*/

#content {}{

float:left;

width:60%;

background:#CCCCCC;

}

/**//*Sidebar*/

#sidebar {}{

float:right;

width:36%;

background:#999999;

}

/**//*Footer*/

#footer {}{

clear:both;

padding:10px;

background:#FFCC33;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航