float浮动定位的特点 & 清除浮float副作用的方法

一、float浮动定位的特点

(1)高度塌陷(父容器不计算float元素的高度)

红色虚线边框的是正常div
蓝色实线边框的是float浮动元素
#box1_1_1 {
    border: 10px dashed red;
    width: 200px;
    height: 100px;
}

#box1_1_2 {
    border: 5px solid blue;
    width: 160px;
    height: 80px;
    float: left;
}

(2)元素覆盖(float元素脱离文档流,导致float元素盖住其它元素,且这种覆盖关系无法通过z-index改变)

蓝色实线边框的是float浮动元素
红色虚线边框的是正常div
#box1_2_1 {
    float: left;
    border: 5px solid blue;
    width: 160px;
    height: 80px;
    z-index: 1;
    /* z-index无法解决float带来的元素遮盖问题 */
}

#box1_2_2 {
    border: 10px dashed red;
    width: 200px;
    height: 100px;
    z-index: 2;
}

(3)浮动元素之间不会重叠

#box1_3_1 {
    width: 200px;
    height: 100px;
    float: left;
    border: 5px solid blue;
}

#box1_3_2 {
    width: 200px;
    height: 100px;
    float: left;
    border: 5px dashed green;
}

#box1_3_3 {
    clear: both;
    /* 用来清除浮动 */
}

(4)浮动元素如果不设置宽度,又没有内容,默认宽度为0(float元素变成了inline-block元素,inline-block的宽高度由内容决定)

第二个float元素
#box1_4_1 {
    float: left;
    border: 5px solid blue;
}

#box1_4_2 {
    float: left;
    border: 5px dashed green;
}

#box1_4_3 {
    clear: both;
    /* 用来清除浮动 */
}
< class="wrap">

二、清除float副作用的方法

(1)添加子元素并设置clear(解决“元素覆盖”+“高度塌陷”)

#box2_1_1 {
    float: left;
    width: 250px;
    height: 200px;
    border: 5px solid blue;
}

#box2_1_2 {
    width: 300px;
    height: 100px;
    border: 10px dashed red;
}

解决效果:

#box2_1_3 {
    float: left;
    width: 250px;
    height: 200px;
    border: 5px solid blue;
}

/* 在float元素后添加一个空的block元素(必须是块级元素),并设置clear属性 */
#box2_1_3_ {
    clear: both;
}

#box2_1_4 {
    width: 300px;
    height: 100px;
    border: 10px dashed red;
}

(2)父元素的after伪元素设置clear(只能解决“高度塌陷”)

#box2_2_1 {
    float: left;
    width: 250px;
    height: 200px;
    border: 5px solid blue;
}

#box2_2_2 {
    width: 300px;
    height: 100px;
    border: 10px dashed red;
}

解决效果:

#box2_2_1 {
float: left;
width: 250px;
height: 200px;
border: 5px solid blue;
}

#box2_2_2 {
width: 300px;
height: 100px;
border: 10px dashed red;
}

#border2_2::after {
    content: '';
    display: block;
    /* 只能为block,不能为inline-block */
    clear: both;
}

(3)父元素触发BFC(只能解决“高度塌陷”)

#box2_3_1 {
    float: left;
    width: 250px;
    height: 200px;
    border: 5px solid blue;
}

#box2_3_2 {
    width: 300px;
    height: 100px;
    border: 10px dashed red;
}

解决效果:

#box2_3_3 {
    float: left;
    width: 250px;
    height: 200px;
    border: 5px solid blue;
}

#box2_3_4 {
    width: 300px;
    height: 100px;
    border: 10px dashed red;
}

#border2_3 {
    overflow: auto;
}
/* 触发BFC有多种方式:
(1)设置overflow属性为auto/sroll/hidden之一,
(2)设置position为fixed/absolute之一,
(3)设置为float,
(4)设置display为inline-block/flex/grid之一 */

(4)子元素触发BFC(解决“元素覆盖”+“高度塌陷”)

解决效果:

#box2_4_3 {
    float: left;
    width: 250px;
    height: 200px;
    border: 5px solid blue;
}
#box2_4_4 {
    width: 300px;
    height: 100px;
    border: 10px dashed red;
    overflow: auto;
}