Search code examples
csscss-float

confusion about float and clear


I have a simple example:

<html>
    <head>
        <title>Float</title>
        <style>
            .name2:after {
                content: "";
                clear: both;
                display: table;
            }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div style="float: left; background-color: red">
                name 1
            </div>
            <div class="name2" style="float: left; background-color: blue">
                name 2
            </div>
            <div style="background-color: purple">
                name 3
            </div>
            <div style="background-color: pink">
                name 4
            </div>
        </div>
        <div>
            next line
        </div>
    </body>
</html>

and the result is the following enter image description here I expected that the div with content "name 3" is below the two floating divs "name 1" and "name 2". Why doesn't the clear: both in the style section have any effect? I know that I can write instead

.name2 + div {
    clear: both;
}

and I get the desired behavior. enter image description here


Solution

  • You cannot clear float by using the clear property on an element that is inside the float element. The clear should be done after and not inside.

    The technique of the pseudo element is generally used on the container that contain all the float elements to clear them since the ::after is placed after them