使用带有clear属性的空元素
在浮动元素后面使用一个空元素来清除浮动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
width: 400px;
background: #1bff18;
}
.item1 {
background: #f71d1a;
width: 100px;
height: 100px;
float: left;
}
.item2 {
background: #ff944f;
width: 100px;
height: 100px;
float: right;
}
.item3 {
background: #e9fd29;
width: 200px;
height: 200px;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="content">
<div class="item1"></div>
<div class="item2"></div>
<div class="clear"></div>
<div class="item3"></div>
</div>
</body>
</html>
overflow: hiden或auto
为浮动元素的容器添加overflow:hiden
或者overflow: auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
width: 400px;
background: #1bff18;
overflow: hidden;
zoom:1
}
.item1 {
background: #f71d1a;
width: 100px;
height: 100px;
float: left;
}
.item2 {
background: #ff944f;
width: 100px;
height: 100px;
float: right;
}
.item3 {
background: #e9fd29;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="content">
<div class="item1"></div>
<div class="item2"></div>
<div class="item3"></div>
</div>
</body>
</html>
与使用空的元素来清除浮动相比,但是item1
会覆盖了item3
给浮动元素容器添加浮动
给浮动元素添加浮动,这样可以清除内部的浮动,但是还会有外部浮动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
width: 400px;
background: #1bff18;
float: left;
}
.item1 {
background: #f71d1a;
width: 100px;
height: 100px;
float: left;
}
.item2 {
background: #ff944f;
width: 100px;
height: 100px;
float: right;
}
.content1 {
background: #e9fd29;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="content">
<div class="item1"></div>
<div class="item2"></div>
</div>
<div class="content1"></div>
</body>
</html>
使用:after的伪元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
width: 400px;
background: #1bff18;
}
.item1 {
background: #f71d1a;
width: 100px;
height: 100px;
float: left;
}
.item2 {
background: #ff944f;
width: 100px;
height: 100px;
float: right;
}
.item3 {
background: #e9fd29;
width: 200px;
height: 200px;
}
.clearfix:after {
content: '';
display: block;
height: 0;
clear: both;
visibility: hidden;
}
</style>
</head>
<body>
<div class="content clearfix">
<div class="item1"></div>
<div class="item2"></div>
<div class="item3"></div>
</div>
</body>
</html>
与使用空的元素来清除浮动相比,但是item1
会覆盖了item3