Unveiling the Mystery of Vertical Misalignment in Inline-Block Elements
Encountering a puzzling CSS issue where an inline-block element's content appears misaligned vertically? The culprit may be the default vertical alignment value.
Inline-block elements have a default vertical alignment of baseline, which aligns the baseline of the box with that of its parent element. This can lead to unexpected alignment when the element contains no in-flow line boxes or has an overflow value other than visible.
Consider the following HTML and CSS:
<div>
#divBottomHeader { height: 43px; } .divAccountPicker { width: 200px; height: 40px; } .divAccountData { width: 400px; height: 40px; }
In this example, the ".divAccountData" element appears shifted downwards compared to ".divAccountPicker." Adding text to ".divPutTextToFixIssue" magically aligns the elements vertically.
This behavior arises from the fact that the baseline of an inline-block element is determined by the baseline of its last line box. By adding text to ".divPutTextToFixIssue," we effectively changed the baseline and forced the alignment to be top.
However, if both blocks contain a different number of lines, the alignment will break again. To ensure consistent vertical alignment, force the alignment using the vertical-align property:
.divAccountData { vertical-align: top; }
This will align the baseline of ".divAccountData" with the top of ".divAccountPicker," regardless of their line count.
The above is the detailed content of Why Are My Inline-Block Elements Vertically Misaligned?. For more information, please follow other related articles on the PHP Chinese website!