使用浮动会容易出现多多少少的问题,如高度塌陷等。所以使用浮动时后面一定要清除浮动,解决浮动带来的问题。
1.使用overflow:hidden;
将兄弟元素强行定为BFC(块级格式化上下文),可以用来占位,解决带来的浮动的问题。
(BFC: block formatting context 块级格式化上下文 - 让元素强制按照块元素的规则进行排列)
<!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>
*{
margin: 0;
padding: 0;
}
.box1{
width: 100px;
height: 100px;
background-color: blue;
float: left;
}
.box2{
width: 300px;
height: 300px;
background-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
2.使用专门清浮动的方式clear:both;
专门设置一个div命名为clearFix,在clearFix里面加入专门清除浮动的方式。
-
注意:这时候box1已经变成块元素了,独占一行显示。
<!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> *{ margin: 0; padding: 0; } .box1{ width: 100px; height: 100px; background-color: blue; float: left; } .box2{ width: 300px; height: 300px; background-color: #000; } .clearFix{ clear: both; } </style> </head> <body> <div class="box1"></div> <div class="clearFix"></div> <div class="box2"></div> </body> </html>
3.父元素使用伪元素::after(万能,推荐)
如果有父元素包含子元素还要清除子元素的浮动,需使用伪类元素::after,在里面添加清除浮动的方法。
-
::after也可以换成:after,兼容性会更好
<!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>
* {
margin: 0;
padding: 0;
}
.box{
border: 3px solid #000;
}
.box1 {
width: 100px;
height: 100px;
background-color: blue;
float: left;
}
.box2 {
width: 300px;
height: 300px;
background-color: red;
float: left;
}
.box3{
width: 100px;
height: 100px;
background-color: #0f0;
float: left;
}
.box::after {
content: "";
display: block;
clear: both;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
<div class="box3">box3</div>
</body>
</html>
-
给box3加了浮动它也不会去到box的左上角,因为box已经清除了浮动。