tags:

views:

1140

answers:

4

I have the following HTML and I would like to display a blue background behind the buttons and text. Unfortunately, with the following code, the blue background disappear. If I remove the CSS for the ids buttons and text, the background is back.

What am I doing wrong?

Thanks!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <style>


    #actions
    {
        background: blue;
    }

    #buttons
    {
        float: left;
    }

    #text 
    {
        float: right;
    }

    </style>
</head>
<body>

        <div id="actions">
            <div id="buttons">
                <input type="button" id="btnOne" value="Bla bla" />
                <input type="button" id="btnTwo" value="Bla bla bls" />
            </div>
            <div id="text">Bla bla bla</div>
        </div>

</body>
</html>
+1  A: 

Try this:

    <div id="actions">
        <div id="buttons">
            <input type="button" id="btnOne" value="Bla bla" />
            <input type="button" id="btnTwo" value="Bla bla bls" />                
        </div>
        <div id="text">Bla bla bla</div>
        <div style="clear:both;height:1px;overflow:none;"></div>
    </div>

The basic problem is that floating elements do not contribute to the calculated height of the container. Thus div#actions doesn't have any height when the other two divs are floated.

Joel Potter
Doesn't work in IE and FF.
Martin
Sorry. Had the div in the wrong place.
Joel Potter
+3  A: 

You have to "clear" your floats. Floating elements takes them out of the normal block positioning of the page, so an element that is floated right breaks out of the parent container, collapsing the div. You can clear them, or the more concise and clever way is to add 'overflow: auto' to the parent container:

#actions
{
    background: blue; overflow: auto;
}

#buttons
{
    float: left;
    overflow: hidden;
}

#text 
{
    float: right;
    overflow: hidden;
}

Since "overflow: auto" can produce scrollbars in certain instances, I usually explicitly prevent that by specifying 'overflow: hidden' on children elements. This works reliably in my experience.

guns
Wow! It works! Thanks! :D
Martin
A: 

More information on floats and clearing them: http://www.dave-woods.co.uk/index.php/float-and-clear-a-comparison-of-css-clearing-techniques/

AaronSieb
A: 

A non-floated element will not have any height if it only contains floated elements. To force the outermost element to stretch down and surround the floated elements it also must be floated. The simple answer to this problem is to float the 'actions' div too- This will extend the background as expected.

Adding an extra element at the bottom just to clear the floated elements is unnecessary and not semantic so it should be discouraged.

Matthew James Taylor