Home » Programming / Coding

Div with float style hiding parent div background color

13 March 2009 6,409 views 3 Comments

Lets start with this code:

<div style=”background:blue;”>

<div style=”float:left;”>some inner div content…</div>

</div>

You might expect the parent div with blue background spanning the width with the inner div content. In reality thats not the case. You would find that there is no parent div with blue background on browser screen. You will see the default background color for <body> or the background color you have set for <body>.

We were expecting to see a left float div content with the parent div filling to the right with the background color.

Why is this happening? When we place any element with left or right float in a div, the parent acts like it did not have anything in it. Meaning it acts like an empty div <div></div>; and since it acts like there is nothing in it it would show 0 height. In other words float elements are taken off the flow.

Solution?

Solution 1: Inside parent div set a div with style clear:both; after the div with float style. That will ensure the parent div retrieve space after the float:left element.

<div style=”background:blue;”>

<div style=”float:left;”>some inner div content…</div>

<div style=”clear:both;”>&nbsp;</div>

</div>

Solution 2: Use a style overflow:hidden for the parent div. That will make it enclose all children.

<div style=”background:blue;overflow:hidden;”>

<div style=”float:left;”>some inner div content…</div>

</div>

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

3 Comments »

  • Carlos said:

    Very Good…

    overflow:hidden apply to me…

    tks…

  • Ankur Rana said:

    This is the best solution i have till now find on the net.
    Thanks keep it up.

  • Mark said:

    glad found this, saved me some time.
    thanks.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.