HTML结构
<div class="parent">
父盒子
<div class="floatLeft">浮动左边盒子</div>
<div class="floatRight">浮动左边盒子</div>
</div>
CSS代码
注:此CSS单纯为了展示居中的效果,不涉及居中的代码,读者可忽略。
.parent {
background: yellow;
}
.floatRight {
float: right;
width: 200px;
height: 200px;
background: red;
margin-top: 10px;
}
.floatLeft {
float: left;
width: 200px;
height: 200px;
background: blue;
margin-top: 10px;
}
原始效果(未清除浮动)
父盒子没撑开,不能将子盒子包裹。
(1)父盒子高度>子盒子高度
.parent {
height:300px;
}
(2)父盒子添加伪元素::after(推荐)
.parent::after{
display: block;
content: "";
clear: both;
}
(3)父盒子添加overflow:hidden
.parent {
overflow:hidden;
}
未截断前的效果