前端清除浮动有哪些方式?
在网页设计中,浮动(float
)属性用于让元素脱离正常文档流,使其向左或向右浮动。但浮动元素可能会导致父元素高度塌陷等布局问题,如下图,父元素的高度由于子元素的浮动没有被撑开,因此需要清除浮动。
以下是几种常见的清除浮动的方式:
1. 使用 clear
属性
clear
属性用于指定元素的哪一侧不允许有浮动元素。可以在浮动元素的后面添加一个空的元素,并为其设置 clear
属性。
HTML 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Float with Empty Element</title>
<style>
.parent {
border: 1px solid red;
}
.float-left {
float: left;
width: 100px;
height: 100px;
background-color: lightblue;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="parent">
<div class="float-left"></div>
<div class="clear"></div>
</div>
</body>
</html>
解释
- 在浮动元素后面添加一个空的
<div>
元素,并为其设置clear: both
,这样可以确保该元素不会与浮动元素在同一行,从而让父元素包含浮动元素。
2. 使用 BFC
(块级格式化上下文)
BFC 是一个独立的渲染区域,规定了内部的块级元素如何布局,并且与外部元素相互隔离。可以通过设置父元素的某些属性来创建 BFC,从而包含浮动元素。
HTML 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Float with BFC</title>
<style>
.parent {
border: 1px solid red;
overflow: auto; /* 创建 BFC */
}
.float-left {
float: left;
width: 100px;
height: 100px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="parent">
<div class="float-left"></div>
</div>
</body>
</html>
解释
- 为父元素设置
overflow: auto
或overflow: hidden
可以创建 BFC,使得父元素包含浮动元素,从而解决高度塌陷问题。
3. 使用伪元素
使用伪元素 ::after
可以在父元素的内容末尾插入一个虚拟元素,并为其设置 clear
属性。
HTML 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Float with Pseudo Element</title>
<style>
.parent {
border: 1px solid red;
}
.parent::after {
content: "";
display: block;
clear: both;
}
.float-left {
float: left;
width: 100px;
height: 100px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="parent">
<div class="float-left"></div>
</div>
</body>
</html>
解释
- 通过
::after
伪元素在父元素的内容末尾插入一个空的块级元素,并设置clear: both
,从而清除浮动。这种方法不需要在 HTML 中添加额外的元素,是比较常用的清除浮动的方式。
4. 直接为父元素设置高度
以下为清除浮动后的效果:
可以看到父元素被子元素的高度撑开;样式正常。