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

前端 未结 1 379
清歌不尽
清歌不尽 2021-01-05 02:54

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 heig

相关标签:
1条回答
  • 2021-01-05 03:32

    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.

    0 讨论(0)
提交回复
热议问题