Make Last Item in div or ul Takes Remaining Width

Have you ever have floated items (div, li, etc.) in a div or ul with a width set to be a percentage? You would have noticed that depending on how the browser handling the rounding of the percentage width to pixel, the last item will usually not be able to take up the remaining width of the containing div or ul.

After some research and finding this post, I've finally laid to rest one of the biggest problem I faced in CSS world.

The key is to activate block formatting contexts. It's quite technical actually, but the solution is actually pretty simple :) I'll go through one way of doing it.

  1. With the following markup:

    <style>
        .item {
            float: left;
            width: 25%;
        }
    </style>
    ...
    <div>
        <!-- remember to clear float! -->
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item">Item 3</div>
        <div class="item">Item 4</div>
    </div>
    
  2. Declare the following style:

    .last-item {
        float: none;
        overflow: hidden;
        width: auto;
    }
    
  3. Replace the class of the last item:

    <div>
        <!-- remember to clear float! -->
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item">Item 3</div>
        <div class="last-item">Item 4</div>
    </div>
    
  4. See the last item magically takes up the remaining width :)