tags:

views:

393

answers:

5

Hello,

<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

Why does the background color not show as black? I cannot set the width and float, is it possible without them?

Thank you for your time.

+4  A: 

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

Lobstrosity
the height trick did it. thank you very much! :) :)
Alec Smart
+1  A: 

Change it to:

<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.

The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:

<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>

Oh and just for completeness, you should really prefer classes to direct CSS styles.

cletus
While lobstrosity's answer is excellent, this is a better solution.You don't have to explicitly declare the height (you may not know it). I also like to use <br style="clear:both" />.
rpflo
A: 

Without floats (and unneccessary divs):

<div style="background-color:black;" onmouseover="this.bgColor='white'">
    hello world
</div>

If you use floats, you have to float the outer div and specify widths.

PatrikAkerstrand
A: 

Floats don't have a height so the containing div has a height of zero.

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

overflow:hidden clears the float for most browsers.

zoom:1 clears the float for IE.

Emily
A: 

You forgot the semi colon! ;;;;;;; put one of these after the word black! Also do what Machine suggested you :)