0

Let's say I have this HTML:

<div id="container">
    <div class="child"></div>
     <div class="child"></div>
     <div class="child"></div>
</div>

...and this CSS:

#container {
    border:1px #ff0000 solid;
    position:relative;
}

#container .child {
    width:200px;
    height:200px;
    background:#f5f5f5;
    float:left;
}

Without using "float", does anyone know how to make #container's height stretch to collective height of all DIV's with class.child?

http://jsfiddle.net/TLxxR/

In case anyone is wondering why, I'm trying to center #container (like this: http://jsfiddle.net/TLxxR/1/) and using "float:left" for example removes the centering.

Andrew
  • 2,691
  • 6
  • 31
  • 47

4 Answers4

2
#container {
    border:1px #ff0000 solid;
    position:relative;
    overflow: hidden;
}

Adding overflow hidden will clear your floats

edit: adding overflow: auto also clears the float if you find that other elements are being cut off

Dennis Fagan
  • 551
  • 4
  • 15
  • Yup, that's the answer. – Andrew Jan 16 '14 at 22:08
  • -1. Using `overflow: hidden` is bad practice simply for clearing floats. Elements may be cut off due to positioning, margins, or CSS3 transforms. It's much more reliable to go with a clearfix. – BenM Jan 16 '14 at 22:12
  • @BenM - can you give an example? – Andrew Jan 16 '14 at 22:13
  • @BenM I would point to this question http://stackoverflow.com/questions/211383/which-method-of-clearfix-is-best. Both solutions are acceptable but you are right my method could cut off content that has been positioned with negative margins etc. – Dennis Fagan Jan 16 '14 at 22:15
  • @Andrew sure. Check out this example using `overflow: hidden` > http://jsfiddle.net/TLxxR/6/ and then this one that uses a clearfix > http://jsfiddle.net/TLxxR/5/ (you'll need to use a WebKit browser to see what I mean). – BenM Jan 16 '14 at 22:23
  • This one uses `overflow: auto` and causes scrollbars: http://jsfiddle.net/TLxxR/7/ – BenM Jan 16 '14 at 22:24
2

You need to use a clearfix:

#container:after {
   display: table;
   content: '';
   clear: both;
}

The complexity of them will depend on the browsers your application needs to support, but the above should get you started.

Here's a great article that explains it a little better and in more details.

And here's a jsFiddle Demo.

BenM
  • 52,573
  • 26
  • 113
  • 168
0

You can add a <div style="clear: both"></div> after last .child.

Dragos Rizescu
  • 3,380
  • 5
  • 31
  • 42
0

Just set the parent to display: inline-block and it will expand with the child.

#container {
  border:1px blue solid;
  position:relative;
  display: inline-block;
}
CJdriver
  • 458
  • 7
  • 20