uber5001
uber5001

Reputation: 3964

Why does overflow: hidden add additional height to an inline-block element?

In this example...

HTML

<body>
  <div>
    <div>foo bar</div>
  </div>
</body>

CSS

body, html, div {
  height: 100%;
  margin: 0;
}
div div {
  display: inline-block;
  overflow: hidden;
}

Why does overflow: hidden cause a vertical scrollbar? Additionally, why is this height not attributed to anything on the page? It's like an invisible margin.

The 100% height of all the elements is intentional. In theory, that should cause the inner-most div to expand to meet the viewport. And it does! ...so long as overflow: hidden is not there, Why?

Upvotes: 26

Views: 13630

Answers (3)

Hewbot
Hewbot

Reputation: 380

Adding overflow: hidden to the parent div wasn't an option for me, and also because of my HTML's structure it wasn't working.

However, I noticed thanks to @Tony Gustafsson's comment in the OP that this does fix the problem:

div div {
    vertical-align: bottom;
}

Upvotes: 11

uber5001
uber5001

Reputation: 3964

The extra height is the same height as the height difference between vertical-align: baseline, and vertical-align: bottom. The "descender line". That's where the seemingly random "5 extra pixels" comes from. If the font size is 10 times as large, this gap will also be 10 times as large.

Also, it seems that when overflow: hidden is not there, the inline-block element has its baseline as the same baseline of its last line of text.

This leads me to believe that overflow: hidden forces the baseline of the entire inline-block element to be at the bottom of the element. Even though there is no text there, the parent of the inline-block element reserves space for the descender line. In the example given in the question, it cannot be easily seen since the parent of the inline-block element has height: 100%. So, instead, that extra space reserved for the descender line overflows out of that parent div.

Why is this space still there, even though there's no text? I think that's because the inline-block creates an inline formatting context, which is what causes this space. Were this element to be a block, it would only create this inline formatting context once it encounters an inline element or text.

This is just a theory, but it seems to explain it. It also explains why @Jonny Synthetic's answer works: adding overflow: hidden to the parent hides that extra descender line.

Thanks to @Hashem Qolami for the jsbins that gave me this theory.

Upvotes: 25

Jonny Synthetic
Jonny Synthetic

Reputation: 51

Items with a height of 100% need to have overflow: hidden as well. The first css rule only targets the outside div, the overflow hidden is being applied to the inside div.

Jsfiddle with this CSS and it worked fine:

body, html, div {
    height: 100%;
    margin: 0px;
    padding:0px;
    overflow: hidden;
}
div div {
    display: inline-block;
    overflow: hidden;
}

Upvotes: 2

Related Questions