Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

html - Why do display: block and display: flex render the same element with a different height?

So I have a div with a span inside. And I'm setting display:block or display:flex on the div, and a small font-size on the span. Surprisingly, this is giving different heights on the div. See the example.

If I set the smaller font-size on the body or div then the height of both is equal. But if I set the smaller font-size on the span like in the example, then the divs get different heights. How come? And can I do anything about it?

span {
  font-size: 0.8rem;
  border: 1px red solid;
}

div {
  border: 1px blue solid;
}
<div style="display: block;">
  <span>test text 1</span>
</div>

<div style="display: flex;">
  <span>test text 2</span>
</div>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In a block formatting context, the line-height property makes a difference.

This is because line-height establishes the minimum height for inline-level elements and line boxes inside block-level containers.

In a block formatting context a span is an inline-level element and line-height applies.

In the code sample, any font size on the span below 1rem will change the font-size, but not the line-height, which remains fixed. That's what you're seeing with font-size: .8rem. The height of the div doesn't change. And it won't change unless the font size exceeds 1rem.

In a flex formatting context, the span is a flex item. A flex item is always a block-level element (regardless of the element type). Flex items are "blockified", according to the flexbox spec. Because there are no inline-level elements, line-height doesn't apply.

Also, an initial setting of a flex container is align-items: stretch. This means that the span sets the height of the container.

In summary, with display: block the line-height keeps the div height fixed. With display: flex, there is no line-height interference and the div tracks the height of the span freely.

One solution: Add display: block to the span, which eliminates the line-height issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...