浮动的破坏性:高度塌陷 浮动元素脱离文档流后,导致父级元素高度塌陷。浮动元素的父级无法包裹住浮动元素。
清除浮动的几种方式
clear 元素的某个方向上不能有浮动元素
.qingfudong{
clear: both;
}
给父级元素加高度
.content{
height: 800px;
}
inline-block清除浮动
display: inline-block;
空标签清浮动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box{
border: 10px solid red;
}
.content{
width: 500px;
height: 300px;
background-color: pink;
float: left;
}
.content1{
width: 500px;
height: 300px;
background-color: pink;
float: right;
}
.clear{
clear: both;
}
a{
display: block;
}
</style>
</head>
<body>
<section class="box">
<div class="content"></div>
<div class="content1"></div>
<!--清浮动的样式写在父级元素的结束标签前-->
<a class="clear"></a>
</section>
</body>
</html>
br的clear属性清浮动
br的clear属性清浮动
缺点:
1、当页面中有很多模块用到浮动,那么每个用到浮动的模块都要加个空标签。
2、不符合W3C标准:结构、样式、行为三者分离
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box{
border: 10px solid red;
}
.content{
width: 500px;
height: 300px;
background-color: pink;
float: left;
}
</style>
</head>
<body>
<section class="box">
<div class="content"></div>
<!--清浮动的样式写在父级元素的结束标签前-->
<br clear="all" />
</section>
</body>
</html>
以浮制浮清浮动
让父级元素也变成浮动元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box{
border: 10px solid red;
float: left;
}
.content{
width: 500px;
height: 300px;
background-color: pink;
float: left;
}
</style>
</head>
<body>
<section class="box">
<div class="content"></div>
</section>
</body>
</html>
:after 清除浮动
:after 在某元素后边添加一个伪节点
必须配合content样式使用
伪节点:
通过伪类动态插入的节点,不会出现在html源文件当中。
和普通节点一样,能设置各类样式。
伪节点默认是内联类型。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box, .box2{
border: 10px solid red;
}
/*.box:after, .box2:after{
content: "";
display: block;
clear: both;
}*/
.content{
width: 500px;
height: 300px;
background-color: pink;
float: left;
}
/*专门清浮动的样式*/
/*IE6,7*/
.clearfix{
*zoom: 1;
}
/*标准浏览器*/
.clearfix:after{
/*after伪类必须配合content样式,否则无效*/
content: "";
/*只有块元素才能清浮动*/
display: block;
/*清浮动的样式clear:both*/
clear: both;
}
</style>
</head>
<body>
<section class="box clearfix">
<div class="content"></div>
</section>
<section class="box2 clearfix">
<div class="content"></div>
</section>
</body>
</html>