Clearing floated images with jQuery

Clearing floated images can actually be a tedious task. Let's say that you have a blog with this post structure:

<p><img src="float.png" alt="Test image" class="alignleft" />Lorem ipsum dolor...</p>
<p>Paragraph after the float.</p>

The class .alignleft is as follows:

.alignleft {

    float: left;
    margin: 3px 5px 0 0;


Since you don't know in advance the dimensions of each floated image, it's likely that you'll end up with both paragraphs surrounding the image, because you don't know in advance how much content will be contained in the first paragraph either. With CSS, you can add the following class to the paragraph containing the image:

.clear {

    overflow: hidden;
    height: 100%;


It works but it's clunky, in the sense that you have to manually add the above class every time a paragraph contains a floated image. We can automate this process with jQuery, like so:

$(document).ready(function() {



For each instance of the .alignleft class, the parent element is automatically cleared with the .clear class. Do more with less. You can see the final result here.

Leave a Reply

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