Why does margin-top work with inline-block but not with inline?
Solution 1:
Section 9.2.4 of the CSS2 specification states:
inline-block
This value causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.inline
This value causes an element to generate one or more inline boxes.
Further on in the CSS2 specification (section 9.4.2) we get told that inline elements only respect horizontal margins (proof):
In an inline formatting context, boxes are laid out horizontally, one after the other, beginning at the top of a containing block. Horizontal margins, borders, and padding are respected between these boxes.
The difference between inline
and inline-block
is that inline
elements are treated as inline whereas inline-block
elements are effectively treated as blocks (which are visually inline with each other).
Block-level elements respect both horizontal and vertical margins whereas inline-level elements only respect horizontal margins.
Solution 2:
The <h1>
tag is by default a block element which allows margins. Using display: inline
turns it into an inline element such as a span tag which does not allow margins.
Using display: inline-block
allows you to use both features of both elements.
Displays an element as an inline-level block container. The inside of this block is formatted as block-level box, and the element itself is formatted as an inline-level box
Reference : w3schools
Solution 3:
Only block level elements can have margins. giving it 'display: inline; forces it (unsurprisingly) to become an inline element, thus losing it's margin.
Try using inline-block if you want to keep it inline with other content and take advantage of margins . . .