美文网首页
CSS-清除浮动

CSS-清除浮动

作者: 测试探索 | 来源:发表于2022-06-11 08:57 被阅读0次

    一、清除浮动

    image.png

    二、代码演示

    2-1: clear: both;(清除左右浮动均可)

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <link rel="stylesheet" type="text/css" href="index.css">
    </head>
    <body>
        <div id="div1">
            <div id="div2"></div>
            <div id="div3"></div>
            <div id="div4"></div>
        </div>
    
    </body>
    </html>
    

    index.css

    #div1{
        background-color: red;
    }
    
    #div2{
        background-color: yellow;
        float: left;
        width: 200px;
        height: 200px;
    }
    
    #div3{
        background-color: blue;
        float: left;
        width: 220px;
        height: 220px;
    }
    
    #div4{
        background-color: black;
        width: 240px;
        height: 240px;
        /*从div4开始,清除该元素之前的浮动*/
        clear: both;
    
    }
    
    2-2: clear: right;(清除右浮动)

    index.css

    #div1{
        background-color: red;
    }
    
    #div2{
        background-color: yellow;
        float: left;
        width: 200px;
        height: 200px;
    }
    
    #div3{
        background-color: blue;
        float: right;
        width: 220px;
        height: 220px;
    }
    
    #div4{
        background-color: black;
        width: 240px;
        height: 240px;
        /*从div4开始,清除该元素之前的浮动*/
        clear: right;
    
    }
    

    2-3:另一种清除方式

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <link rel="stylesheet" type="text/css" href="index.css">
    </head>
    <body>
        <div id="div1">
            <div id="div2"></div>
            <div id="div3"></div>
            <div id = "clearDiv"></div>
            <div id="div4"></div>
        </div>
    
    </body>
    </html>
    

    index.css

    #div1{
        background-color: red;
    }
    
    #div2{
        background-color: yellow;
        float: left;
        width: 200px;
        height: 200px;
    }
    
    #div3{
        background-color: blue;
        float: right;
        width: 220px;
        height: 220px;
    }
    
    #div4{
        background-color: black;
        width: 240px;
        height: 240px;
    
    
    }
    
    #clearDiv::after{
        content:"";
        visibility: hidden;
        height: 0px;
        display: block;
        clear: both;
    }
    
    }
    
    image.png

    相关文章

      网友评论

          本文标题:CSS-清除浮动

          本文链接:https://www.haomeiwen.com/subject/tglhmrtx.html