CSS 小结笔记之清除浮动

浮动是一个非常好用的属性,但是有时会出现一些问题,需要进行清除浮动。例如

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
 
        .fa {
            background-color: red;
            width: 600px;
            /* height: 600px; */
        }
        
        .son1 {
            width: 200px;
            height: 200px;
            background-color: aqua;
            float: left;
        }
        
        .son2 {
            width: 300px;
            height: 200px;
            background-color: pink;
            float: left;
        }
        
        .div2 {
            width: 700px;
            height: 100px;
            background-color: orange;
        }
    </style>
</head>

<body>

    <div class="fa">aaa
        <div class="son1"></div>
        <div class="son2"></div>
    </div>
    <div class="div2"></div>
</body>

</html>
View Code

在父盒子没有给出高度的情况下,子盒子浮动不会将父盒子撑开来。

清除浮动使用clear:left|right|both 一般使用clear:both,具体方法如下:

1、在浮动标签后边添加一个额外的clear标签例如<div style="clear:both"></div>这样做的方法
例如
<body>
    <div class="fa">aaa
        <div class="son1"></div>
        <div class="son2"></div>
        <div style="clear:both"></div>
    </div>
    <div class="div2"></div>
</body>
View Code

结果如下,这种方法简单明了,但是会增加额外的标签

2、父级添加overflow:hidden|auto|scroll 
在.fa 的css属性中增加overflow:hidden ,结果也如上图所示,例如
.fa {
            background-color: red;
            width: 600px;
            overflow: hidden;
        }
这种方法方便快捷,但是元素内容多时易造成不会自动换行导致内容被隐藏掉,无法显示需要溢出的元素

3、使用after伪元素进行清除浮动

   .clearfix:after {
            content: ".";
            /* 最好给content制定一个值防止旧版浏览器有空隙 */
            display: block;
            height: 0;
            visibility: hidden;
            clear: both;
        }
        
        .clearfix {
            *zoom: 1;
            /* 星号代表是ie6、ie7能识别的特殊符号
            zoom 是ie6、ie7清除浮动的方法*/
        }

这样给父盒子增加一个clearfix  类即可实现1中的图片效果。

4、同时使用after和before清除浮动
        .clearfix:before,
        .clearfix:after {
            content: "";
            display: table;
        }
        .clearfix:after {
            clear: both;
        }
        
        .clearfix {
            *zoom: 1;
        }
           

用法和方法三一样,给父元素增加clearfix 类即可

第3、4种方法都是目前常用的方法,不增加多余标签,但是ie6和ie7不支持after,需要使用zoom:1来清除浮动

 
原文地址:https://www.cnblogs.com/Assist/p/9592825.html