浮动要封闭到一个盒子当中,否则就会对页面后续的元素产生影响
清除浮动
一、overflow: hidden
不加overflow: hidden前
给父元素添加overflow: hidden后
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
/* 让内部有浮动的父盒子形成BFC,它就能关闭住内部的浮动 */
div {
overflow: hidden;
margin: 10px;
}
p {
width: 100px;
height: 100px;
background-color: pink;
margin-right: 10px;
float: left;
}
.red {
background-color: red;
}
</style>
</head>
<body>
<div>
<p></p>
<p></p>
</div>
<div>
<p class="red"></p>
<p class="red"></p>
</div>
</body>
</html>
二、clear: both(不推荐)
在两个父盒子之间添加一个属性为clear: both;的盒子
clear 表示清除浮动对自己的影响,both 表示左右浮动都清除
给浮动后面的元素添加clear: both;后
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
margin: 10px;
}
p {
width: 100px;
height: 100px;
background-color: pink;
margin-right: 10px;
float: left;
}
.blue {
background-color: blue;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="box">
<p></p>
<p></p>
</div>
<div class="clear"></div>
<div class="box">
<p class="blue"></p>
<p class="blue"></p>
</div>
</body>
</html>
三、伪元素::after(强烈推荐)
给盒子添加最后一个子元素添加 ::after伪元素
并且给 ::after 设置 clear:both;
添加伪元素::after后
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
margin: 10px;
}
.box::after {
content: "";
clear: both;
/* 转化为块级元素 */
display: block;
}
p {
width: 100px;
height: 100px;
background-color: pink;
margin-right: 10px;
float: left;
}
.yellow {
background-color: yellow;
}
</style>
</head>
<body>
<div class="box">
<p></p>
<p></p>
</div>
<div class="box">
<p class="yellow"></p>
<p class="yellow"></p>
</div>
</body>
</html>