DEV Community

Heru Hartanto
Heru Hartanto

Posted on • Edited on

Don't use float

Of course you can use float don't be silly, but use it wisely because you have to pay it with clearfix ๐Ÿ™€

here what I mean

<div style="
    background: blue;
    display: block;
    clear: both; // put clear here for extra protection if there are any float before this element ๐Ÿ˜”
    overflow: hidden; // put this too ๐Ÿ˜ญ
"><p>container here </p>
    <div style="background:red;float:left;height: 100px;width: 100px;">child 1</div>
    <div style="background:red;float:left;height: 100px;width: 100px;">child 2</div>
    <div style="background:red;float:left;height: 100px;width: 100px;">child 3</div>
</div>
Enter fullscreen mode Exit fullscreen mode

when we make a website, sometimes we have to create two div that divided equally to container width, our approach usually something like this

    <div class="container">
        <div style="
            float: left;
            width: 50%;
            background: red;
        ">
            div a
        </div>
        <div style="
            float: right;
            width: 50%;
            background: blue;
        ">
            div b
        </div>
    </div>
Enter fullscreen mode Exit fullscreen mode

it's fine but when this element getting more complex, it's hard to make it proper unless you put clear at your container, to solve this issue use flex instead

<div class="container" style="
    display: flex;
    justify-content: space-evenly;
">
    <div style="background:red;width: 50%;">div a</div>
    <div style="background:blue;width: 50%;">div b</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
afif profile image
Temani Afif

clear:both on the parent container is useless. clear is used to clear previous floating element not child floating elements