为什么要去除浮动?
蓝色的div块因为浮动脱离文档流而挡住了红色div的显示,因此我们需要去除浮动让红色div块显示在蓝色div块下面
<style>
.box1{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
.box2{
width: 300px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
现在效果
目标结果
1.给浮动的元素的祖先元素加上高度
<style>
.father{
height: 200px;
}
.box1{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
.box2{
width: 300px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="father">
<div class="box1"></div>
</div>
<div class="box2"></div>
</body>
2.使用after伪元素(作用于父级)清除浮动(推荐使用)
.father::after{
content: '';
height: 0;
visibility: hidden;
display: block;
clear: both;
}
.box1{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
.box2{
width: 300px;
height: 100px;
background-color: red;
}
3.父级添加overflow属性(父元素添加overflow:hidden)
.father{
overflow: hidden;
}
.box1{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
.box2{
width: 300px;
height: 100px;
background-color: red;
}
4.在最后一个浮动标签后,新加一个标签,给其设置clear:both;
<style>
.clear{
clear: both;
}
.box1{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
.box2{
width: 300px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="clear"></div>
<div class="box2"></div>
</body>