CSS清除浮动
- 什么是浮动?
元素的浮动指的是设置浮动属性的元素会脱离文档流,移动到父元素的指定位置。 - 元素怎么实现浮动?
元素的水平浮动,只能在水平方向上浮动,属性有left和right;
一个浮动元素会尽量向左向右移动,直到它的外边缘会遇到其他包含框或另一个浮动框的边框为止。(找离它最近的父级元素,不包含内边距<元素不会浮动到父级元素的边框上>);
浮动元素之后的元素将围绕它,浮动元素之前的元素将不会受到影响。 - 如何清除浮动?
清除浮动有三种方法:
(1)在想清除浮动的地方添加一个div标签,在div标签中写一个类名如:class=“clear”,并在style中写上.clear{clear:both}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>float</title>
<style>
.box {
border: 1px solid red;
}
.item {
width: 100px;
height: 100px;
float: left;
}
.one {
width: 100px;
background-color: pink;
}
.two {
height: 200px;
width: 200px;
background-color: yellowgreen;
}
.three {
height: 300px;
background-color: lightblue;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<!-- 盒子在计算浮动时不会计算浮动子元素的高度 -->
<div class="box">
<div class="item one"></div>
<div class="item two"></div>
<div class="item three"></div>
<div class="clear"></div>
</div>
</body>
</html>
(2)通过伪元素来清除浮动。在父元素后添加一个伪元素after,将after中的content内容设为空,设置clear:both;将显示模式改成块级display:block。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>float</title>
<style>
.box {
border: 1px solid red;
}
.box::after {
content: '';
clear: both;
display: block;
}
.item {
width: 100px;
height: 100px;
float: left;
}
.one {
width: 100px;
background-color: pink;
}
.two {
height: 200px;
width: 200px;
background-color: yellowgreen;
}
.three {
height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<!-- 盒子在计算浮动时不会计算浮动子元素的高度 -->
<div class="box">
<div class="item one"></div>
<div class="item two"></div>
<div class="item three"></div>
</div>
</body>
</html>
(3)给父级元素添加一个高度,但是高度被写实后不能随着子元素的高度而自动撑开。因此不推荐使用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>float</title>
<style>
.box {
height: 300px;
border: 1px solid red;
}
.item {
width: 100px;
height: 100px;
float: left;
}
.one {
width: 100px;
background-color: pink;
}
.two {
height: 200px;
width: 200px;
background-color: yellowgreen;
}
.three {
height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<!-- 盒子在计算浮动时不会计算浮动子元素的高度 -->
<div class="box">
<div class="item one"></div>
<div class="item two"></div>
<div class="item three"></div>
</div>
</body>
</html>
PS:只要设置了浮动,最好都要记得清除浮动。