在做网页时经常会碰到元素的自动清除浮动问题,现记下两种解决方法。设有网页元素如下:
<div class="container">
<div class="left">
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
</div>
<div class="right">
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
</div>
</div>
若要class值为“container”中的两个元素分别左右浮动,则需以下CSS代码:
div.container{
width:100%;
background:#ff9;
}
div.left{
width: 45%;
float: left;
}
div.right {
width: 45%;
float: right;
}
常用清除浮动的CSS代码如下:
.container:after{
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.container{
display:inline-block;
}
/* Hides from IE-mac \*/
* html .container {height: 1%;}
.container {display: block;}
/* End hide from IE-mac */
刚开始用上面这段代码时觉得很方便,因为不用在html文件里再加个清除浮动的元素了,但就是难记。终于有一天在怿飞的博客里找到更方便的写法,只需给container元素加个“overflow”属性就可以了。出自http://www.quirksmode.org/css/clearing.html。
div.container{
width:100%;
background:#ff9;
overflow: auto;
width:100%;
}
div.left {
width: 45%;
float: left;
}
div.right {
width: 45%;
float: right;
}
如果要为container元素加上一个最小高度应该怎么办呢?很简单,对于IE6及其以下版本的IE游览器直接加个高度就可以了。如果高度超过了IE会自动增加高度以适应内容,而对于高级游览器则加min-height属性就可以了。代码如下:
div.container{
background:#ff9;
overflow: auto;
height:auto;
_height:20px;
min-height:20px;
}
div.left {
width: 45%;
float: left;
}
div.right {
width: 45%;
float: right;
}
下面是演示代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<style type="text/css">
div.container{
background:#ff9;
overflow: auto;
height:auto;
_height:20px;
min-height:20px;
}
div.left {
width: 45%;
float: left;
}
div.right {
width: 45%;
float: right;
}
</style>
<title></title>
</head>
<body>
<div><div class="container">
<div class="left">
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
左浮动元素<br />
</div>
<div class="right">
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
右浮动元素<br />
</div>
</div></div>
</body>
</html>