以下案例会造成浮动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.father {
width: 400px;
border: 1px solid pink;
}
.father > .son {
width: 100px;
height: 100px;
background-color: skyblue;
}
.father > .left {
float: left;
}
.father > .right {
float: right;
}
</style>
</head>
<body>
<div class="father">
<div class="son left"></div>
<div class="son right"></div>
</div>
</body>
</html>
解决办法
1.给父元素添加clearfix类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.father {
width: 400px;
border: 1px solid pink;
}
.father > .son {
width: 100px;
height: 100px;
background-color: skyblue;
}
.father > .left {
float: left;
}
.father > .right {
float: right;
}
/* 清除浮动 */
.clearfix::after {
content: '';
display: block;
clear: both;
}
</style>
</head>
<body>
<div class="father clearfix">
<div class="son left"></div>
<div class="son right"></div>
</div>
</body>
</html>
2.给父元素添加overflow:hidden属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.father {
overflow: hidden;
width: 400px;
border: 1px solid pink;
}
.father > .son {
width: 100px;
height: 100px;
background-color: skyblue;
}
.father > .left {
float: left;
}
.father > .right {
float: right;
}
</style>
</head>
<body>
<div class="father">
<div class="son left"></div>
<div class="son right"></div>
</div>
</body>
</html>