Sunday, October 25, 2009

Float left doesn't expand parent DIV

Float left doesn't expand parent DIV
A very common cross browser issue I've seen has been with floating DIVs. This is one of those inconsistencies between the popular browsers that a web developer has to keep in mind every time they develop a new CSS layout. It's very frustrating to create a layout and set a div to float left, but it doesn't expand it's parent DIV if you expect it to. Well it's not supposed to. If you develop in internet explorer you may expect that to work but if you try it in other browsers you will quickly be corrected.

For example. If you are developing your site in Internet Explorer or Opera, not sure why you would, you may do something like the following:

<style>
.container
{
   width:300px;
   background-color:green;
}
.box
{
   float:left;
   width:100px;
   height:100px;
   border:3px solid red;
}
</style>
<div class="container">
   <div class="box"></div>
   <div class="box"></div>
</div>

Now, if you were developing this in IE or Opera, you would think all is well.


But, you may be unaware of the results in Firefox, Safari, and Chrome.



Firefox, Safari, and Chrome all think that a floating div should not stretch the size of its parent div. While IE and Opera think that if a floating div is larger than its parent div, it should stretch. The whole goal to writing a layout like this is for it to work in all of the main browsers. In order to do that you need to write something that they all understand. For this problem, the solution is easy. To accommodate both ideas, all you have to do is use the CSS attribute called overflow and set it to hidden on the "container" div.

So the correct code would look something like this:

<style>
.container
{
   width:300px;
   background-color:green;
   overflow:hidden;
}
.box
{
   float:left;
   width:100px;
   height:100px;
   border:3px solid red;
}
</style>
<div class="container">
   <div class="box"></div>
   <div class="box"></div>
</div>
Now in all browsers your result is:

NOTE: the code I write in my articles are not HTML strict. It is just to get you started. If you want to use it, it is best practice to put the proper HTML tags to accompany my code.

1 comment: