浮动: 非IE浏览器下,容器不设高度 且子元素浮动时,容器高度不能被内容撑开。 此时,内容会溢出到容器外面而影响布局。这种现象被称为浮动(溢出)。
浮动元素脱离文档流,不占据空间,引起“高度塌陷”
<style>
.father{width: 400px;background-color: yellow;border: 1px solid black;}
.son{width: 100px;height: 100px;background-color: red;float: left;}
</style>
<div class="father">
<div class="son"></div>
</div>
<p>123</p>
清除浮动的方法:
1、包含浮动元素的父级标签添加overflow:hidden或者overflow:auto
<style>
.father{
width: 400px;background-color: yellow;border: 1px solid black;
overflow: hidden; /* BFC */
}
.son{width: 100px;height: 100px;background-color: red;float: left;}
</style>
<div class="father">
<div class="son"></div>
</div>
<p>123</p>
2、给父级div定义height属性:height: 100px;
<style>
.father{
width: 400px;background-color: yellow;border: 1px solid black;
height: 100px;
}
.son{width: 100px;height: 100px;background-color: red;float: left;}
</style>
<div class="father">
<div class="son"></div>
</div>
<p>123</p>
3、最后一个浮动元素之后添加一个空的div标签,并添加clear:both样式
<style>
.father{width: 400px;background-color: yellow;border: 1px solid black;}
.son{width: 100px;height: 100px;background-color: red;float: left;}
.clear{clear: both;}
</style>
<div class="father">
<div class="son"></div>
<div class="clear"></div>
</div>
<p>123</p>
4、使用 ::after 伪元素:.clearFix::afte
<style>
.father{width: 400px;background-color: yellow;border: 1px solid black;}
.son{width: 100px;height: 100px;background-color: red;float: left;}
.clearFix::after{
content: "";
clear: both;
display: block;
}
</style>
<div class="father clearFix">
<div class="son"></div>
</div>
<p>123</p>