clear:both - please explain...

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
konrados
Forum Newbie
Posts: 17
Joined: Tue Apr 29, 2008 9:32 am

clear:both - please explain...

Post by konrados »

Hi,
I had a following simple html code:

Code: Select all

 
<div style="width:100%;border:1px solid green;">
    <div style="float:left;border:solid 1px blue">  on the left     </div>
</div>
 
But it didn't work, even though I think I've done this about a hundred times before. The container (with green border) is above the nested div.

I tried adding div style="clear:both"... just after the left-floating div but it didn't work either.

After trial and error, adding br style="clear:both" finally worked:

Code: Select all

 
<div style="width:100%;border:1px solid green;">
    <div style="float:left;border:solid 1px blue">  on the left     </div>
    <br style="clear:both" />
</div>
 
But can somebody explain me why? Why do we actually need to add this "clear:both" stuff, and why it has to be on "br" tag? Maybe there is somewhere a good article about divs? It looks like I completely don't understand them. I thought that whatever I will put in the "container" div, this container will expand to the contents, whatever the contents will be. Now it seems I have to add some strange stuff...

p.s. I have another code where div style="clear:both" works fine and does the job - why in this particular case I need to use br style="clear both". I would love to finally understand the way divs work...
matthijs
DevNet Master
Posts: 3360
Joined: Thu Oct 06, 2005 3:57 pm

Re: clear:both - please explain...

Post by matthijs »

In short: a floated element is "taken out of the flow", so to speak. It's parent element collapses. Unless it's cleared. And that can be done in several ways.

The method you use, setting an extra element like br and giving it a clear:both; does work. It can be any element, a p, h2, div, ul, etc
But there are other methods to obtain the same effect. Google "easy clearing css" or something and you'll find many examples. What I often do is float the parent element as well.

Code: Select all

 
<div style="float:left;width:100%;border:1px solid green;">
    <div style="float:left;border:solid 1px blue">  on the left     </div>
</div>
konrados
Forum Newbie
Posts: 17
Joined: Tue Apr 29, 2008 9:32 am

Re: clear:both - please explain...

Post by konrados »

OK, I'll play now with divs, thanks!
Post Reply