前端开发基础之CSS选择器——清除浮动

清除浮动的简介

主要含义:清除浮动带来的影响
原因: 子元素浮动后脱标→不占位置。
目的: 需要设置高度,从而不影响其他网页元素的布局。

清除浮动的方法

方法一:直接设置高度

优缺点:
优点:简单粗暴,方便。
缺点:有些布局中不能固定父元素高度。如:新闻列表、京东推荐模块。

    <style>
        .father {
            width: 400px;
            height:500px;
            background-color: red;
        }
        .son {
            float: left;
            width: 100px;
            height: 400px;
            background-color: green;
        }
    </style>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>

方法2:额外标签法

1.在父元素内容的最后添加一个块级元素
2. 给添加的块级元素设置 clear:both
特点:
缺点:会在页面中添加额外的标签,会让页面的HTML结构变得复杂

    <style>
        .father {
            width: 400px;
            background-color: red;
        }
        .son {
            float: left;
            width: 100px;
            height: 400px;
            background-color: green;
        }
        .aaa {
            clear: both;
        }
    </style>
<body>
    <div class="father">
        <div class="son"></div>
        <div class="aaa"></div>
    </div>
</body>

方法3:单伪元素清除法

操作:用伪元素替代了额外标签
(1)基本写法:

    <style>
        .father {
            width: 400px;
            background-color: red;
        }
        .son {
            float: left;
            width: 100px;
            height: 400px;
            background-color: green;
        }
        .father::after {
            content: '';
            display: block;
            clear: both;
        }
    </style>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>

(2)补充写法:

    <style>
        .clearfix::after {
            content: '';
            display: block;
            clear: both;
            /* 补充代码:在网页中看不到伪元素 */
            height: 0;
            visibility: hidden;
        }
    </style>
<body>
    <div class="father clearfix">
        <div class="son"></div>
    </div>

方法4:双伪元素清除法

特点:
优点:项目中使用,直接给标签加类即可清除浮动。
操作:

    <style>
        .clearfix::before,
        .clearfix::after{
            content: '';
            display: table;
        }
        .clearfix::after {
            clear: both;
        }
    </style>
<body>
    <div class="father clearfix">
        <div class="son"></div>
    </div>
</body>

after可以用来解决浮动,before可以用来解决盒子上部的塌陷现象。

方法5:给父元素设置overflow : hidden

直接给父元素设置overflow : hidden

    <style>
        .father {
            width: 400px;
            height:500px;
            background-color: red;
            overflow: hidden;
        }
        .son {
            float: left;
            width: 100px;
            height: 400px;
            background-color: green;
        }
    </style>
<body>
    <div class="father">
        <div class="son"></div>
    </div>

小编刚开始写,如有错误可在评论区留言及时更正哦~
欢迎大家留言!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值