在进行网页设计时,往往父元素的高度由其子元素的高度决定,造成了父元素为自适应高度,而在对子元素设置float属性后后,造成父元素高度为0,会造成高度塌陷。
举一个简单的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>float元素浮动</title>
<style type="text/css">
/*父元素不设置高度,但子元素设置浮动不占用原文档流的位置*/
.father {
width: 800px;
border: 2px solid #535758;
margin: 0px auto;
}
.child1 {
float: left;
width: 300px;
height: 200px;
background-color: purple;
}
.child2 {
float: left;
width: 200px;
height: 200px;
background-color: pink;
}
.child3 {
float: left;
width: 400px;
height: 200px;
background-color: palegreen;
}
.child4 {
float: left;
width: 300px;
height: 200px;
background-color: orangered;
}
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
</div>
</body>
</html>
由于父元素没有高度,不能包裹住子元素,效果就会变成这样:
因此,我们要清除浮动元素造成的影响。
清除浮动本质
清除浮动其实也很简单,只需要在父元素的最后一个孩子加上clear:both属性,父级元素就会根据浮动的子盒子自动检测高度,就不会影响下面的标准流了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>float元素浮动</title>
<style type="text/css">
/*父元素不设置高度,但子元素设置浮动不占用原文档流的位置*/
.father {
width: 800px;
border: 2px solid #535758;
margin: 0px auto;
}
.child1 {
float: left;
width: 300px;
height: 200px;
background-color: purple;
}
.child2 {
float: left;
width: 200px;
height: 200px;
background-color: pink;
}
.child3 {
float: left;
width: 400px;
height: 200px;
background-color: palegreen;
}
.child4 {
float: left;
width: 300px;
height: 200px;
background-color: orangered;
}
/*最后一个子元素设置clear:both即可*/
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
<div class="clear"></div>
</div>
</body>
</html>
效果图如下: