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?

Roy Tang
  • 5,643
  • 9
  • 44
  • 74

3 Answers3

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 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 Jul 22 '10 at 12:10
  • @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 Jul 22 '10 at 12:16
  • 1
    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 Jul 22 '10 at 13:37
  • @Paul - I completely agree, and a decent replacement for `
    ` 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 Jul 22 '10 at 13:47
  • Did `
    ` ever do variable width centering? I guess it did with tables?
    – Paul D. Waite Jul 22 '10 at 13:51
3

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

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

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

ExE Boss
  • 126
  • 1
  • 4