浮动副作用
当元素设置float浮动后,该元素就会脱离文档流并向左向右浮动
- 浮动元素会造成父元素高度塌陷
- 后续元素会受到影响
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="text"></div>
.container {
width: 500px;
background-color:gray;
}
.box{
width: 100px;
height: 100px;
background-color:aqua;
margin: 5px;
}
.text{
width: 100px;
height: 100px;
background-color: blueviolet;
}
这是没有加浮动的效果,由于没有设置灰色容器的高度,所以他的高度就是所有子元素撑开的大小
当给三个蓝色的box设置了浮动后,灰色容器直接消失了(高度变成了0)紫色方块 跑到了底下和蓝色方块重叠了。
清除浮动
当父元素出现塌陷的时候,对布局是不利的,所以我们必须清除副作用,解决方案有多种
- 父元素设置高度
- 受影响的元素增加clear属性
- overflow清除浮动
- 伪对象方式
父元素设置高度
如果父元素高度塌陷,可以给父元素设置高度,撑开元素本身大小
受影响的元素增加clear属性
通过设置高度,确实能让灰色块正常显示了,
但是如果把紫色方块和蓝色方块放到同一层级,由于蓝色方块设置了浮动,紫色方块没有设置浮动,还是出现了问题
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="text"></div>
</div>
.container {
width: 500px;
height:500px;
background-color:gray;
}
.box{
width: 100px;
height: 100px;
background-color:aqua;
margin: 5px;
float: left;
}
.text{
width: 100px;
height: 100px;
background-color: blueviolet;
}
添加上clear
属性,both
代表清除左右浮动
.text{
width: 100px;
height: 100px;
background-color: blueviolet;
clear: both;
}
这样就可以正常显示了
overflow清除浮动
如果有父级塌陷,并且同级元素也受到了影响,可以使用overflow
清除浮动
这种情况下父布局不能设置高度
父级标签的样式里面加:overflow:hidden;clear:both;
.container {
width: 500px;
background-color:gray;
overflow: hidden;
clear: both;
}
伪对象方式
如果有父级塌陷,同级元素也受到了影响,还可以使用伪对象方式处理
为父级标签添加伪类after
,设置空的内容,并使用clear:both;
这种情况下,父布局不能设置高度
.container::after{
content:"";
display: block;
clear: both;
}