[html] Why does background-color have no effect on this DIV?

<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?

This question is related to html css

The answer is


This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer element in my case didn't show. I added a position: relative which worked.


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.


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.