一、未设置子元素浮动的效果。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box{
background-color:red;
width:100%;
}
.box1{
width:50%;
height:200px;
background-color:blue;
text-align:center;
line-height:200px;
font-size:50px;
}
.box2{
width:50%;
height:200px;
background-color:#03A9F4;
text-align:center;
line-height:200px;
font-size:50px;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
</html>
二、设置子元素浮动效果。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box{
background-color:red;
width:100%;
}
.box1{
width:50%;
height:200px;
background-color:blue;
text-align:center;
line-height:200px;
font-size:50px;
}
.box2{
width:50%;
height:200px;
background-color:#03A9F4;
text-align:center;
line-height:200px;
font-size:50px;
}
.box>div{
float:left;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
</html>
可以看到设置子元素浮动以后,box父元素高度塌陷了,没有高度了。
三、解决子元素浮动导致的父元素塌陷问题(清除浮动)。
1、给父元素box后面添加伪元素清除浮动,设置.box::after
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box{
background-color:red;
width:100%;
}
.box1{
width:50%;
height:200px;
background-color:blue;
text-align:center;
line-height:200px;
font-size:50px;
}
.box2{
width:50%;
height:200px;
background-color:#03A9F4;
text-align:center;
line-height:200px;
font-size:50px;
}
.box>div{
float:left;
}
.box::after{
content:"";
display:block;
clear:both;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
</html>
可以看到高度被子元素撑开了200px。
2、直接给box父元素添加overflow:auto;或者overflow:hidden属性
.box{
background-color:red;
width:100%;
overflow:auto;
}
父元素高度同样也可以被子元素撑开。
3、设置父元素box属性float: left,让父元素同样脱离文档流。