清除浮动的方式:
第一种是clear:both/left/right,需要在浮动元素后面再加一个元素,设置其css为clear
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div{
background:pink;
}
#one{
width:200px;
height:200px;
background:greenyellow;
float:left;
margin-left:30px;
}
#two{
clear:left;
}
</style>
</head>
<body>
<div id="con">
<div id="one">float1</div>
<div id="two"></div>
</div>
</body>
</html>
第二种是overflow:auto在父元素里加overflow
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#one{
width:200px;
height:200px;
background:greenyellow;
float:left;
margin-left:30px;
}
#con{
background:pink;
overflow:auto;
}
</style>
</head>
<body>
<div id="con">
<div id="one">float1</div>
</div>
</body>
</html>
第三种是使用after伪元素
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#con{
background:greenyellow;
}
#a{
width:200px;
height:200px;
float:left;
background:purple;
}
#con:after{
content: "";
display: block;
clear:both;
}
</style>
</head>
<body>
<div id="con">
<div id="a">aaa</div>
:after
</div>
</body>
</html>
注:浮动布局会使父元素高度为0,在未设置高度的情况下高度不会随着子元素的高度变化,所以要清除浮动