清除浮动的几种方式

 1.额外标签法

在最后一个浮动标签后面,添加一个额外的标签,设置为clear:both;属性

适合用于清除兄弟元素间的浮动

<style>
        .son{
            width: 100px;
            height: 100px;
            float: left;
        }
        .box{
            width: 100px;
            height: 100px;
            background-color: red;
        }
        .clearfix{
            clear: both;
        }
    </style>
    <div class="son1 son" style="background-color: aqua;"></div>
    <div class="son2 son" style="background-color: aquamarine;"></div>
    <!-- 清除浮动的额外盒子 -->
    <div class="clearfix"></div>
    <div class="box"></div>

2.父级添加overflow属性

将父元素添加overflow:hidden;属性

只适合父子元素之间清除浮动,不适合含有内容较多的父级(容易导致内容隐藏,无法显示要溢出的元素)

 <style>
        .father{
            overflow: hidden;
        }
        .son {
            width: 100px;
            height: 100px;
            float: left;
        }
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
    <div class="father">
        <div class="son1 son" style="background-color: aqua;"></div>
        <div class="son2 son" style="background-color: aquamarine;"></div>
    </div>
    <div class="box"></div>

注:上述代码中,如果.box的div位于.father的div内部(不是作为兄弟元素),还是会被浮动覆盖

3.使用after伪元素清除浮动

给浮动元素的父元素的伪元素添加相应属性

只适合父子元素之间清除浮动(如果.box的div位于.father的div内部,和上一种方法一样还是会被浮动覆盖)

<style>
        .clearfix::after{
            content: '';
            display: block;
            clear: both;
            visibility: hidden;
        }
        .son {
            width: 100px;
            height: 100px;
            float: left;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
    <div class="father clearfix">
        <div class="son1 son" style="background-color: aqua;"></div>
        <div class="son2 son" style="background-color: aquamarine;"></div>
    </div>
    <div class="box"></div>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值