149

I have the following in my CSS. All margins/paddings/borders are globally reset to 0.

#wrapper{width: 75%; min-width: 800px;}
.content{text-align: justify; float: right; width: 90%;}
.lbar{text-align: justify; float: left; width: 10%;}

Now when I write my HTML as

<div id="wrapper">
    <div class="content">
        some text here
    </div>
    <div class="lbar">
        some text here
    </div>
</div>

the page renders correctly. However, when I inspect the elements, div#wrapper is shown as being 0px high. I would've expected it to expand till the end of div.content and div.lbar... Why does this happen?

Again, the page renders fine. This behaviour just perplexes me.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
  • 5
    This might be useful to you [CSS Floats 101](http://www.alistapart.com/articles/css-floats-101/), from [A List Apart](http://www.alistapart.com/). – David Thomas Mar 20 '11 at 17:02

4 Answers4

276

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

That Brazilian Guy
  • 3,328
  • 5
  • 31
  • 49
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 2
    [Here's another approach](https://css-tricks.com/snippets/css/clear-fix/) for making containers contain floats that is solved in CSS without having to add elements to the page. – Phil Aug 22 '17 at 21:17
62

Ordinarily, floats aren't counted in the layout of their parents.

To prevent that, add overflow: hidden to the parent.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 16
    Thanks, this works, but I don't understand why ... overflow:hidden is said to _hide_ the content that overflows, not to enlarge the element to contain it. – ripper234 May 23 '11 at 04:16
  • @ripper234 Here is why: http://stackoverflow.com/questions/25818199/why-does-overflow-hidden-add-additional-height-to-an-inline-block-element – kristianp Apr 24 '15 at 03:24
10

I'm not sure this is a right way but I solved it by adding display: inline-block; to the wrapper div.

#wrapper{
    display: inline-block;
    /*border: 1px black solid;*/
    width: 75%;
    min-width: 800px;
}

.content{
    text-align: justify; 
    float: right; 
    width: 90%;
}

.lbar{
    text-align: justify; 
    float: left; 
    width: 10%;
}
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Melih
  • 666
  • 1
  • 9
  • 24
  • 3
    This was the exact solution i've been looking for. Overflow: hidden cause box shadow to vanish, naturally. – Kitiara Jun 03 '20 at 23:13
1

Now, you can

#wrapper { display: flow-root; }
Jehong Ahn
  • 1,872
  • 1
  • 19
  • 25