1.浮动元素的父级元素如果定义了高度,就不需要清除浮动了。(新闻的内容长短不确定,高度不确定,就需要清除浮动)
2.浮动元素要定义宽高,否则会影响后续元素的浮动效果。
空div标签清除浮动.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.header,.main,.footer{
width:500px;
}
.header,.footer{
height: 100px;
background: #000;
}
.main{
background: #eee;
margin: 10px 0;
}
.content{
width: 300px;
height: 300px;
background: orange;
float: left;
}
.sidebar{
width: 190px;
height: 300px;
background: green;
float: right;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="main">
<div class="content"></div>
<div class="sidebar"></div>
<div style="clear:both;"></div> <!--在最后的浮动元素后,用空的div标签清除浮动-->
</div>
<div class="footer"></div>
</body>
</html>
父标签的overflow清除浮动.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.header,.main,.footer{
width:500px;
}
.header,.footer{
height: 100px;
background: #000;
}
.main{
background: #eee;
margin: 10px 0;
overflow:hidden; /*浮动元素的父级标签 overflow属性清除浮动。(bfc) (弊端:超出父元素之外的内容会隐藏) */
}
.content{
width: 300px;
height: 300px;
background: orange;
float: left;
}
.sidebar{
width: 190px;
height: 300px;
background: green;
float: right;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="main">
<div class="content"></div>
<div class="sidebar"></div>
</div>
<div class="footer"></div>
</body>
</html>
伪元素清除浮动.html(建议使用该方法):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.header,.main,.footer{
width:500px;
}
.header,.footer{
height: 100px;
background: #000;
}
.main{
background: #eee;
margin: 10px 0;
}
.content{
width: 300px;
height: 300px;
background: orange;
float: left;
}
.sidebar{
width: 190px;
height: 300px;
background: green;
float: right;
}
.clearfix:after{ /*伪元素清除浮动。父级元素引用clearfix类*/
content:"."; /*可以为空*/
display: block;
height: 0;
line-height: 0;
visibility: hidden;
clear:both; /*清除浮动*/
}
.clearfix{ /*兼容ie浏览器*/
zoom:1;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="main clearfix"> <!--浮动标签的父级元素引用clearfix类-->
<div class="content"></div>
<div class="sidebar"></div>
</div>
<div class="footer"></div>
</body>
</html>
伪元素清除浮动的另一种写法.css:
.clearfix:before, .clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1; /*IE/7/6*/
}