浮动
使元素浮动和绝对定位,都会脱离文档流
使元素浮动:
- 设置 float 属性,不为 none。 虽然脱离了文档流但是仍然会占据位置。
- 设置
position: absolute;
。脱离文档流并且不占位。
浮动的好处
- 文字环绕效果
- 双飞翼布局
- ...
清除浮动
清除浮动的方式有很多,这里就介绍些我用过比较好的
- clear:both;
下面是综合设置,推荐使用,使用方式:<div class="clearfix"></div>
/* 清除浮动 */
.clearfix::before,
.clearfix::after{
content: "";
display: block;
height: 0;
line-height: 0;
visibility: hidden;
clear: both;
}
- overflow: hidden;
设置overflow: hidden;
有两个作用:
- 溢出隐藏
- 设置当前元素 为绝缘容器,不受其它元素影响,也不影响其它元素。这里的影响主要指元素浮动产生的影响。
也就是说,当一个元素,因为它的兄弟元素浮动(这里指 float )而被影响了,可以给这个元素添加overflow: hidden;
,使它不受其它元素影响。
谁需要清除浮动
有时候,为了排版需要,一个父级元素里的所用子元素都脱离了文档流,导致父级元素高度塌陷,此时,就需要给父级元素清除浮动。以保证和父级并级的其它元素不会排版错乱。