CSS清除浮动的方法

目录

前言

一、设置父节点高度

二、给父节点加overflow:hidden

三、在浮动元素后添加一个clear:both的元素

四、在父元素内添加伪元素::after

五、在父元素内添加双伪元素::after,::before

总结


前言

为什么需要清除浮动?因为会存在以下情况:当父节点不设置高度时,子节点设置高度且设置浮动,脱离了标准流,此时父节点会高度塌陷。影响布局

如图:

正常状态下父节点未设置高度,子节点撑起了父节点

给子节点设置浮动后

.parent {
    width: 150px;
    border: 1px solid red;
}
.son {
    width: 100px;
    height: 100px;
    background-color: orange;
    float: left;
}

一、设置父节点高度

直接给父节点一个高度,优点是简单方便,但缺点是有时候节点无固定高度。

给父节点设置高度为120px

.parent {
    width: 150px;
    border: 1px solid red;
    height: 120px;
}
.son {
    width: 100px;
    height: 100px;
    background-color: orange;
    float: left;
}

二、给父节点加overflow:hidden

.parent {
    width: 150px;
    border: 1px solid red;
    overflow: hidden;
}
.son {
    width: 100px;
    height: 100px;
    background-color: orange;
    float: left;
}

三、在浮动元素后添加一个clear:both的元素

clear 属性指定元素两侧不能出现浮动元素

.parent {
    width: 150px;
    border: 1px solid red;
}
.son {
    width: 100px;
    height: 100px;
    background-color: orange;
    float: left;
}
.clear {
    clear: both;
}

<div class="parent">
    <div class="son"></div>
    <div class="clear"></div>
</div>

四、在父元素内添加伪元素::after

.parent {
    width: 150px;
    border: 1px solid red;
    &::after {
        display: block;
        content: ''; //content 属性与 :before 及 :after 伪元素配合使用,来插入内容。
        clear: both;
        visibility: hidden; //会使对象看不见,但在网页中所占的空间仍然存在
    }
}
.son {
    width: 100px;
    height: 100px;
    background-color: orange;
    float: left;
}

五、在父元素内添加双伪元素::after,::before

.parent {
    width: 150px;
    border: 1px solid red;
    &::before,
    &::after {
        content: '';
        display: table;
    }

    &::after {
        clear: both;
    }
}
.son {
    width: 100px;
    height: 100px;
    background-color: orange;
    float: left;
}

总结

以上五种方法则是清除浮动常见的方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值