Div Class Clear – Without the Markup

The Div Class Clear is an old trick for getting container backgrounds to stretch down to the bottom of its contents. Although there has since been a push for the “float nearly everything” technique, I’m not convinced that constantly setting floats and widths across all elements is a sustainable method. Instead, let’s address the only problem people have with the Div Class Clear method – the added markup.

We can remove this markup quite simply with jQuery. Rather than mess with the actual on-page elements, why not insert it dynamically? Check out the code:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type="text/javascript">
    $(document).ready(function(){
$("*:last-child").filter(function() {
return $(this).css('float') != 'none';
}).parent().append("<div class='clear'></div>");
    });
</script>
<style>
.clear {clear:both;}
</style>

Note: As you may imagine, this method assumes that the viewer has javascript enabled. Given that the downside is a matter of background stretching, and considering all the numerous other things that break when javascript isn’t enabled, I (generally) readily accept this sacrifice. After all, it’s not like Flash, where they get no content at all.