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

青春壹個敷衍的年華 提交于 2020-01-11 08:56:12

问题


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;
}

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

<div style="display: flex;">
  <span>test text 2</span>
</div>

回答1:


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.



来源:https://stackoverflow.com/questions/47439665/why-do-display-block-and-display-flex-render-the-same-element-with-a-different

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!