tags:

views:

27

answers:

2

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: alt text

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

+1  A: 

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

Pekka
+4  A: 

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.

Nick Craver
Will this work for all browsers? I don't have access to a Windows machine at the moment, so can't test IE.
Roy Tang
`overflow: hidden` also works
Ryan Kinal
@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.
Nick Craver
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 D. Waite
@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.
Nick Craver
Did `<center>` ever do variable width centering? I guess it did with tables?
Paul D. Waite