Inline vs. Inline-Block: Why Margin-Top Only Works with Inline-Block
The Question
When using HTML and CSS, a user attempts to create a top margin for an
element, but it only appears when the CSS property display is set to inline-block, not when it's set to inline.
Explanation
The CSS specification defines the difference between inline and inline-block as follows:
-
inline-block: Creates an inline-level block container where the element's internal content is formatted as a block box, and the element itself is formatted as an inline-level box.
-
inline: Generates one or more inline boxes.
Crucially, the CSS2 specification states that inline elements only respect horizontal margins (e.g., margin-left).
The Distinction
The difference lies in how inline and inline-block elements are treated:
- While inline elements are considered true inline elements, inline-block elements are treated as blocks, but are visually inline with one another.
- Block-level elements (like inline-block) respect both horizontal and vertical margins, while inline elements only respect horizontal margins.
Resolution
Therefore, in the case provided, setting display to inline on the
element only applies horizontal margins, which does not include margin-top. Setting display to inline-block, however, allows both horizontal and vertical margins to be applied, including margin-top.
The above is the detailed content of Why Doesn\'t Margin-Top Work on Inline Elements but Does on Inline-Block Elements?. For more information, please follow other related articles on the PHP Chinese website!