目录
什么是盒子塌陷-demo展示
这是我想要的效果:
但是我却得到了......:
子级的两个盒子跑到了父级的边框外面 。
这是因为父级盒子没有设置固定高度,是靠子级盒子撑起来的。
子级盒子float浮动后,脱离了正常的文档流,不能再将父级盒子撑起,导致塌陷。
小tip:还有就是,float浮动最初被设计的初衷是为了实现文字环绕效果,现在也被用作布局工具。
5种具体解决方法
- 父级同时浮动
- 给父级添加固定高度
- 父盒子里最下方引入清除浮动块:<div style="clear:both;"></div> 或者 <br style="clear:both;">
- 父级设置overflow:hidden属性(比较常用)
- 通过after伪类:
父级元素选择器::after {
content: "";
clear: both;
display: block;
height: 0;
}
demo代码
HTML:
<div class="father">
<div class="left" style="background-color: aqua;"></div>
<div class="right" style="background-color: aquamarine;"></div>
</div>
CSS:
.father {
width: 500px;
border: 5px solid red;
margin: 20px auto;
/* 解决父级塌陷 */
overflow: hidden;
}
.father div {
width: 50%;
height: 200px;
float: left;
}