Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a simple example in which an outer DIV contains an inner DIV which has
display: inline-block;.
Because I have set the height of the inner div, I expect the outer div to take on the same height as the inner div. Instead, the outer div is slightly taller, as you can see from the fiddle. Question: Why is this happening and how can I "fill up" the outer div without setting its height explicitly?
My goal is to have the outer div expand and shrink based on the height of the inner.

.outer {
  background-color: red;
}
.inner {
  display: inline-block;
  width: 480px;
  height: 140px;
  background-color: green;
}
<div class="outer">
  <div class="inner"></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
389 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your .inner div has display: inline-block. That means it needs an inline formatting context around it. Inline layout produces struts, which make room for descenders. You can see how it fits if you put a character next to the .inner element: http://jsfiddle.net/bs14zzeb/6/

The default vertical-align is to have the bottom edge of the inline-block box lined up with the baseline of the surrounding text. Even if there is no surrounding text, the layout engine still has to make room for an entire line of text.

That's why these answers are suggesting that you play with the vertical-align property. Setting it to vertical-align: top, as one answer suggests, tells the layout engine to align the top edge of the inline-block box with the top edge of the line box. Here, since the line height is less than 140px tall, it gets rid of the extra space on the bottom. But if the height of a line is taller than that, you'll still have extra space underneath: http://jsfiddle.net/bs14zzeb/9/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...