Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div collapse when using float [duplicate]

Tags:

html

css

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">
<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>
like image 901
Martin Avatar asked Mar 12 '09 18:03

Martin


2 Answers

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.

like image 128
guns Avatar answered Sep 22 '22 06:09

guns


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.

like image 34
Joel Avatar answered Sep 24 '22 06:09

Joel