当父元素不给高度的时候,且内部元素不浮动,父元素的高度由子元素的高度撑开;内部元素浮动的时候,父元素会变成一条线。
为什么要清除浮动?
为了解决父元素因为子元素浮动引起的高度塌陷为0的问题
清除浮动的方法:
(1)额外标签法(添加无意义标签,语义化差)
在最后一个浮动标签后面,新加一个标签,并设置clear:both;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清除浮动</title>
<style>
.father {
width: 400px;
}
.left {
float: left;
background-color: red;
width: 200px;
height: 200px;
}
.center {
float: left;
background-color: green;
width: 110px;
height: 300px;
}
.right {
float: left;
background-color: blue;
width: 90px;
height: 100px;
}
.footer {
width: 500px;
height: 100px;
background-color: #666;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="father">
<div class="left">左左左</div>
<div class="center">中</div>
<div class="right">右右右</div>
<!-- 额外标签法 -->
<div class="clear"></div>
</div>
<div class="footer"></div>
</body>
</html>
(2)父级添加overflow:hidden
通过触发BFC的方式,实现清除浮动
缺点:子元素增多的时候,容易造成不会自动换行,内容被隐藏掉,无法显示元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清除浮动</title>
<style>
.father {
width: 400px;
/* 父元素添加overflow属性 */
overflow: hidden;
}
.left {
float: left;
background-color: red;
width: 200px;
height: 200px;
}
.center {
float: left;
background-color: green;
width: 110px;
height: 300px;
}
.right {
float: left;
background-color: blue;
width: 90px;
height: 100px;
}
.footer {
width: 500px;
height: 100px;
background-color: #666;
}
</style>
</head>
<body>
<div class="father">
<div class="left">左左左</div>
<div class="center">中</div>
<div class="right">右右右</div>
</div>
<div class="footer"></div>
</body>
</html>
(3)使用after伪元素清除浮动(推荐使用)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清除浮动</title>
<style>
.father {
width: 400px;
}
.left {
float: left;
background-color: red;
width: 200px;
height: 200px;
}
.center {
float: left;
background-color: green;
width: 110px;
height: 300px;
}
.right {
float: left;
background-color: blue;
width: 90px;
height: 100px;
}
.footer {
width: 500px;
height: 100px;
background-color: #666;
}
/* 使用after伪元素清除浮动 */
.clearfix:after {
content: '';
display: block;
height: 0;
clear: both;
visibility: hidden;
}
/* 兼容IE6 */
.clearfix {
*zoom: 1;
}
</style>
</head>
<body>
<!-- 添加clearfix样式 -->
<div class="father clearfix">
<div class="left">左左左</div>
<div class="center">中</div>
<div class="right">右右右</div>
</div>
<div class="footer"></div>
</body>
</html>
(4)给浮动元素的父级设置高度