CSS tutorial for Blogger users: handling floated images

Handling floated images can be actually a tedious task, especially when we don't want that the elements following those images be still affected by floating. For example, if you have a markup like this:

<p><img src="image.png" alt="Image" class="alignleft" />Paragraph content.</p>

In this case, it's very likely that the elements coming after the paragraph are still affected by floating, because the content of the paragraph is not sufficient to contain the floated image. You can easily fix this problem by adding the following class to the paragraph:

.cleared {
  overflow: hidden;
  height: 100%; /* IE6 */
}

However, you still have to add this class manually. You can automate this task by using jQuery. For example:

$(document).ready(function() {

    $('img').each(function() {

      var $img = $(this);

        if($img.hasClass('alignleft') {
             
              $img.parent().addClass('cleared');
        }

    });

});

By doing so, floated images inside paragraphs are automatically cleared and contained.

Leave a Reply

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