一、在列表最后加一个子元素列表项,然后清除浮动。
<!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>
.left {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.right {
width: 100px;
height: 100px;
background-color: orange;
float: right;
}
.clearfix {
clear: both;
}
</style>
</head>
<body>
<div>
<div class="left"></div>
<div class="right"></div>
<div class="clearfix"></div>
</div>
<p>哈喽你好</p>
</body>
</html>
二、对父元素使用伪元素
<!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>
.left {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.right {
width: 100px;
height: 100px;
background-color: orange;
float: right;
}
.parent::after {
display: block;
content: "";
clear: both;
}
</style>
</head>
<body>
<div class="parent">
<div class="left"></div>
<div class="right"></div>
</div>
<p>哈喽你好</p>
</body>
</html>
三、给列表加一个高度
<!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>
.left {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.right {
width: 100px;
height: 100px;
background-color: orange;
float: right;
}
.parent {
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="parent">
<div class="left"></div>
<div class="right"></div>
</div>
<p>哈喽你好</p>
</body>
</html>
四、给父元素添加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>
.left {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.right {
width: 100px;
height: 100px;
background-color: orange;
float: right;
}
.parent {
overflow: hidden;
}
</style>
</head>
<body>
<div class="parent">
<div class="left"></div>
<div class="right"></div>
</div>
<p>哈喽你好</p>
</body>
</html>