Search code examples
cssimagemargin

Why does the img tag accept the margin-top property?


I am wondering why img tag accept margin top property? isn't this an inline tag? and inline tags does't accept top and bottom margins?


Solution

  • It's because img is an inline replaced element and it does accept margin-top. It behaves differently than inline non-replaced element (like span for example).

    Related part of the specification detailing this: https://www.w3.org/TR/CSS21/visudet.html#inline-replaced-height

    Note that there is no restriction or special behavior related to margin unlike with non-replaced inline element where you can read:

    The vertical padding, border and margin of an inline, non-replaced box start at the top and bottom of the content area, and has nothing to do with the 'line-height'. But only the 'line-height' is used when calculating the height of the line box.

    Same logic for width/height. They work with img but not with span.

    Another related question dealing with transform where the same logic apply: CSS transform doesn't work on inline elements