CSS: how opposite floats work

As web developers, we're usually accustomed to use CSS floats only in simple ways in order to build our layouts. Sometimes, however, floats get more complicated especially when we use a combination of left and right values.

To start our little journey inside opposite floats, let's draw a simple HTML skeleton:

<div id="container">

<div class="row">

<div class="alignleft"></div>
<div class="alignright"></div>

</div>

<div class="row">

<div class="alignleft"></div>
<div class="alignleft"></div>
<div class="alignleft"></div>
<div class="alignright"></div>
<div class="alignright"></div>
<div class="alignright"></div>


</div>


<div class="row">

<div class="alignleft"></div>
<div class="alignright"></div>
<div class="alignleft"></div>
<div class="alignright"></div>
<div class="alignleft"></div>
<div class="alignright"></div>


</div>


<div class="row">

<div class="alignleft"></div>
<div class="alignright"></div>
<div class="alignright"></div>
<div class="alignleft"></div>
<div class="alignright"></div>
<div class="alignright"></div>


</div>

<div class="row">

<div class="alignright"></div>
<div class="alignleft"></div>
<div class="alignright"></div>
<div class="alignleft"></div>
<div class="alignright"></div>
<div class="alignleft"></div>


</div>

</div>

with really basic styles:

#container {

    width: 600px;
    margin: 0 auto;

}

div.row {

    height: 100%;
    overflow: auto;
    padding-bottom: 1em;
    

}

div.alignleft {

    float: left;
    width: 100px;
    height: 100px;
    background: green;

}

div.alignright {

    float: right;
    width: 100px;
    height: 100px;
    background: orange;

}

We have a container with five rows of floated elements. More precisely, we're taking into account some possible combinations of left-floated and right-floated elements (from two up to six). So we have:

  1. First row: left-right
  2. Second row: left-left-left-right-right-right
  3. Third row: left-right-left-right-left-right
  4. Fourth row: left-right-right-left-right-right
  5. Fifth row: right-left-right-left-right-left

You can see the results in the following picture.

As you can see, in some cases result differs from what we did expect (the only noticeable change is in the 4th row). In such cases, the best approach is testing some possible combinations of floats to make ourselves clear what it's actually happening under the hood.}

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.