HTML代码结构:
<div class="box">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>
CSS代码样式:
.box{
border: 1px solid #ccc;
background: #fc9;
color: #fff;
margin: 50px auto;
padding: 50px;
}
.div1{
width: 80px;
height: 80px;
background: red;
float: left;
}
.div2{
width: 80px;
height: 80px;
background: blue;
float: left;
}
.div3{
width: 80px;
height: 80px;
background: sienna;
float: left;
}
方法一:给浮动的元素添加兄弟元素,并且给兄弟元素添加clear:both
HTML:
<div class="box">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="clear"></div>
</div>
CSS:
.clear{
clear:both;
height: 0;
}
方法二:给浮动元素的父元素添加over-flow:hidden
CSS:
.box{
overflow:hidden;
zoom:1; //处理兼容问题
}
方法三:给浮动元素的父元素添加单伪元素
CSS:
.box{
zoom:1;
} /*==for IE6/7 Maxthon2==*/
.box:after {
centent:"";//设置内容为空
height:0;//高度为0
line-height:0;//行高为0
display:block;//将文本转为块级元素
visibility:hidden;//将元素隐藏
clear:both//清除浮动
} /*==for FF/chrome/opera/IE8==*/
其中clear:both;指清除所有浮动;content: '.'; display:block;对于FF/chrome/opera/IE8不能缺少,其中content()可以取值也可以为空。visibility:hidden;的作用是允许浏览器渲染它,但是不显示出来,这样才能实现清楚浮动。
方法四:给浮动的元素的父元素添加双伪元素
.clearfix:before,.clearfix:after {
content: "";
display: block;
clear: both;
}
.clearfix {
zoom: 1;
}