Search code examples
htmlcsscss-floatclearfix

HTML/CSS: Clear floating elements in the middle without adding unneeded tags


Most of the clearfix techniques out there involves adding things at the very bottom of the parent container, and I prefer the pseudo element approach the most since it doesn't add unneeded elements into the HTML.

However, recently I found that I am dealing with a container that has some children floating but not all. Say the first 2 children the first floats left and the second floats right. I need a way to clear the float right after the second element, so the content below doesn't get squeezed in between them. Is there a way to clear floating elements in the middle but without adding clearfix element?

Below is an example:

HTML

<div class="container">
    <div class="child">
        first child!
    </div>
    <div class="child">
        second child!
    </div>
    <div class="child">
        third child!
    </div>      
</div>

CSS

.container {
    width: 200px;
}

.child:nth-child(1) {
    float: left;
    background: yellow;
}

.child:nth-child(2) {
    float: right;
    background: red;
}

.child:nth-child(3) {
    background: blue;
    color: white;
}

Please see this jsfiddle to see what I have right now.


Solution

  • Just use clear: both; on the 3rd element, this way you don't have to use <div style="clear: both;"></div> after the floated elements.

    .child:nth-child(3) {
        background: blue;
        color: white;
        clear: both;
    }
    

    Demo


    Also, if whenever you are looking to clear a parent element without adding an extra element or using overflow: hidden; which is a dirty way to clear floats, you can call a class on the parent element, with the properties below

    .clear:after {
       content: "";
       display: table;
       clear: both;
    }
    

    For example

    <div class="wrapper clear">
        <div class="left_floated_div"></div>
        <div class="right_floated_div"></div>
    </div>