jQuery and CSS: clearing floats

Note This post is the natural completion of a previous post about jQuery and containing floats.

I've set up a sample page where you can see the float property in action. The list that contains the floated elements has been deliberately left without any clearing class applied to it. Now it's time to fix it using jQuery. Why jQuery? Because we don't want to manually add a class to the list, that's all.

Using jQuery

The jQuery code required here is very short, as usual:

$(document).ready(function() {
  $('*').each(function() {
    $that = $(this);
    if($that.css('float') !== 'none') {
   $that.parent().addClass('clearfix');
    }
  });
});

The above code loops through all the elements of the page and when it encounters an element that has the float property set to a value different from none, it applies the clearfix class to its parent. Do more with less!

Leave a Reply

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