Home > Article > Web Front-end > Why Do Empty Inline-Block Divs Have Height?
Why Inline-Block Sets a Height for Empty Divs
When an empty div element is assigned the display property "inline-block," it unexpectedly exhibits a gain in height, a phenomenon that doesn't occur with "display:block." This seemingly paradoxical behavior stems from the inherent characteristics of inline-block formatting.
Line-Height Calculation in Inline-Block
Upon setting an element to inline-block, line-height calculations undergo a transformation. Instead of aligning bases of text within, inline-block aligns bottoms, tops, or both.
Line Height for Empty Inline-Block
For empty inline-block elements, the line-height calculation is derived from the font metrics associated with the element. However, since there's no text content, this results in the element assuming a basic line-height based on the font size it inherits from its parent element (typically the body).
Fixing the Empty Inline-Block Height
To eliminate the unwanted height caused by the inherited line-height, one can employ a wrapper element that explicitly sets the font-size to 0, effectively nullifying any line-height calculation:
.wrapper { font-size: 0; }
.wrapper div { font-size: medium; }
Update: Height of Empty Inline-Block
It's important to note that the height of an empty inline-block element has no official documentation. However, observations reveal a pattern.
Minimum Line Space Reservation
Inline-block elements seem to reserve a minimum line space regardless of having content. This space is based on the inherited line-height from the parent element.
Implications
This behavior suggests that inline-block inherently expects content and reserves a default line space for it, even if it's empty. While this contradicts the W3 specifications for zero-height empty line boxes, it's a quirk specific to inline-block formatting.
The above is the detailed content of Why Do Empty Inline-Block Divs Have Height?. For more information, please follow other related articles on the PHP Chinese website!