Sámal Rasmussen
Sámal Rasmussen

Reputation: 3495

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>

Upvotes: 12

Views: 10504

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371113

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.

Upvotes: 22

Related Questions