清除浮动是为了解决浮动元素对父容器高度塌陷的问题。以下是一些常用的清除浮动的手法和示例:
1. 空元素清除浮动(clearfix):
通过在浮动元素的父容器最后添加一个空的块级元素,并应用 clear: both;
样式,来清除浮动。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clearfix Example</title>
<style>
.float-left {
float: left;
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<div class="float-left"></div>
<div class="float-left"></div>
<div class="clearfix"></div>
<p>Text after floated elements.</p>
</body>
</html>
2. 使用 overflow
属性:
通过在浮动元素的父容器上添加 overflow: hidden;
或 overflow: auto;
,来清除浮动。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Overflow Example</title>
<style>
.float-left {
float: left;
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
}
.clearfix {
overflow: hidden; /* 或 overflow: auto; */
}
</style>
</head>
<body>
<div class="float-left"></div>
<div class="float-left"></div>
<div class="clearfix"></div>
<p>Text after floated elements.</p>
</body>
</html>
3. 使用 display: flow-root;
:
通过在浮动元素的父容器上添加 display: flow-root;
属性,来创建一个新的块级格式化上下文(BFC),从而清除浮动。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flow-Root Example</title>
<style>
.float-left {
float: left;
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
}
.clearfix {
display: flow-root;
}
</style>
</head>
<body>
<div class="float-left"></div>
<div class="float-left"></div>
<div class="clearfix"></div>
<p>Text after floated elements.</p>
</body>
</html>
上述三种方法都可以用来清除浮动,选择其中一种取决于具体的需求和项目的要求。在现代Web开发中,Flexbox 和 Grid 等新的布局方式也逐渐替代了传统的浮动布局,而清除浮动的需求也减少。