Banishing <div class='clear'>
Penned on .
When dealing with floating containers in HTML and CSS, we all too often turn to the clearing div to make a clean break between container rows. I'm sure you've seen this before:
<div class="clear"></div>
and in the css:
div.clear { clear: both; }
Sure, it works. It always has worked and it always will. It's not the most elegant solution, though; it's not semantic and with enough floated containers it can really start to clutter up your markup.Enter the "overflow: hidden" trick. It's not a silver bullet nor will it work in every single situation but it might just save you some markup by using some that you probably already have.
It goes a little something like this. If your floated containers happen to share a common parent (like a wrapper div, or maybe you've got a bunch of floated list items contained in a ul or ol tag) simply set the width of the parent and apply the attribute "overflow: hidden" like so:
<!-- the html -->
<div class="parent">
<p class="column-1">
This is column one
</p>
<p class="column-2">
This is column two
</p>
</div>
/* the css */
.parent {
width: 400px;
overflow: hidden
}
.column-1 {
width: 180px;
float: left;
}
.column-2 {
width: 180px;
float: right;
}
"Surely that can't work," you might say, "the content in the parent element will be clipped!" On the contrary: by not giving the parent container an explicit height only the horizontal space is constrained; the parent will stretch to accommodate its contents while clearing out any elements that aren't contained within it resulting in something a little like this (colors and padding added for demonstration):
So there you have it, a simple and effective alternative to the clear div