问题
html:
<div class="f-box">
<div class="box1"></div>
<div class="box2"></div>
</div>
css:
.f-box {
background-color: pink;
}
.box1,
.box2 {
width: 200px;
height: 200px;
}
.box1 {
float: left;
background: tomato;
}
.box2 {
float: left;
background: greenyellow;
}
效果:
父元素没有被撑开,所以没有显示出来。
解决办法
一、添加空标签
在元素末尾加一个空标签并且设置样式clear: both
html:
<div class="f-box">
<div class="box1"></div>
<div class="box2"></div>
<div style="clear: both"></div>
</div>
二、将父元素设置为BFC
设置父元素样式overflow: hidden;
或者display: flex;
等等。创建BFC
.f-box {
background-color: pink;
overflow: hidden;
}
三、使用伪元素
设置父元素after
伪元素清除浮动
其实这种方式类似第一种,只是用为元素代替了空标签
.f-box::after{
content:'';
display:block;
height:0;
clear:both;
visibility:hidden;
}