关于CSS中的clear:both的理解和错误的用法


传智播客在2016年的web教学视频中,讲到了clear:both清除浮动的用法

DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>title>
        <style>
            #div1{
                width: 500px;
                height: 300px;
                border: 1px solid red;
                float: left;
                
            }
            #div2{
                width: 500px;
                height: 300px;
                border: 1px solid black;
            }
            #div3{
                width: 500px;
                height: 300px;
                border: 1px solid pink;
            }
            #div0{
                
                clear: both;
            }
        style>
    head>
    <body>
        
        <div id="div1">div>
        
        <div id="div2">div>
        
        <div id="div3">div>
    body>
html>

他的本意是DIV2和DIV3不受DIV1浮动的影响,但是他将float属性加在了DIV1上面导致该属性不能生效,这是因为:

在 css 文档里面规定 clear:both 的意思是:要求框的顶边框边低于在源文档中之前生成的任何浮动框的底外边距边。

所以有 clear:both 属性的元素放在浮动元素之后才能起到清除浮动的作用。

对于 clear 属性一定要牢记的是:

clear只能清除该元素之前的浮动。 
"clear on an element only clears the floats before it in document order. It doesn't clear floats after it."

清除浮动的方式有不少,不过最常见,也是最优化的一种就是就是使用伪元素:

  Parent :after{
        clear:both;
        display:block;
        content:"";
    }