Hello everyone,
Today i would like to show you guys a much cleaner way to solve a common problem that is pretty often solved by using
a clearfix div.
A dirty way
In a nutshell, when you have a container div (or block element) and you set a width but not a height (or vice versa) no matter what size the inner elements are the container will not shrink wrap around the inner contents. So if you would have set a background color or image, you will not see it since the height is 0. To solve this someone came up with a solution to add
an extra div inside the container that has a property of clear:both.
Quite often it's combined with the property display:none;
A sample could look like this:
Code:
<style>
#container{
width:300px;
}
.clearfix{
clear:both;
}
</style>
<div id="container">
<div id="child"><p>lalalala</p></div>
<div class="clearfix"></div>
</div>
A cleaner way
Now this may seem okay, but it can be done much cleaner without having to add an extra div and class. Assuming we have set a fixed width (but not a height) to div#container just like above all we need to do is give that container a property of
overflow:hidden; Making the markup look like below, which needless to say is much cleaner.
Code:
<style>
#container{
width:300px;
overflow:hidden;
}
</style>
<div id="container">
<div id="child"><p>lalalala</p></div>
</div>
What it does in fact say is, anything that becomes wider or higher than the set width or height will be hidden. Since we did not set a height it will just shrink wrap around the content and show everything.
Now after you read this, you may think this makes sense and only idiots would use the clearfix version. Well Think again: Quite some big companies use this clearfix.... Why? Probably because of the same reason why IE 5,6,7 and 8 sucked so much and cost us so much time extra when making nice websites. Curious what big companies. Well here you are:
http://www.microsoft.com/about/en/us/default.aspx
View their source code and see for yourself.
Moreover, not only are they using the clearfix, but also tables to create the layout. Hopefully you guys already
know that tables are meant for other stuff. Despite the promising IE 9, their website is a bad example.
Hopefully you guys found this useful! As always if you have questions, comments or request, feel free to post them.
Cssfreakie