7

Say I have the following HTML:

<head>
    <style>
        #container {
            border: 1px red solid;
        }
        .floaty {
            width: 200px;
            float: left;
            border: 1px green solid;
        }
    </style>
</head>
<body>
<div id='container'>
    Text inside the container
    <div class='floaty'>
    Floaty block 1<br/>
    Floaty block 1<br/>
    Floaty block 1<br/>
    </div>
    <div class='floaty'>
    Floaty block 2<br/>
    Floaty block 2<br/>
    Floaty block 2<br/>
    </div>
    <div class='floaty'>
    Floaty block 3<br/>
    Floaty block 3<br/>
    Floaty block 3<br/>
    </div>
</div>
</body>

This renders as: floaty divs

What's the proper CSS way to have the container (red-bordered box) completely surround the floaty green-bordered boxes?

0

3 Answers 3

20

Add an overflow: auto to the container, like this:

#container {
     border: 1px red solid;
     overflow: auto;
}

You can test the effect here, and find a very good description of how it works here.

Sign up to request clarification or add additional context in comments.

5 Comments

Will this work for all browsers? I don't have access to a Windows machine at the moment, so can't test IE.
@Roy - You may have to give the element a width in IE for it to behave correctly, just depends which versions you have to support.
It’s worth commenting your use of overflow to indicate that it’s intended to contain floats. Although this behaviour is correct as per the spec, it’s not the obvious result of applying overflow. I wish there was a contain-floats: contain; properly in CSS.
@Paul - I completely agree, and a decent replacement for <center> as well. It seems completely ridiculous to me that this still isn't in CSS3. I'm well aware you can do it, but there's no simple replacement for variable width centering.
Did <center> ever do variable width centering? I guess it did with tables?
3

add overflow: auto to the container or apply a clearfix.

Comments

0

On modern browsers, you can use display: flow‑root; or the contain property, which are the non‑hackish way to do this:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.