Differences in behaviour between padding and margin

and border, for good measure.

  1. An element can have a margin, which is some space around the element
    Content
  2. or a padding, which is also space around the element.
    Content
  3. So at first sight it looks like margin and padding are interchangeable, but that's not quite true.
    The margin is outside of the padding. Having both a padding and a margin increases the space around the element.
    Content
  4. Vertical margins collapse, that is, adjacent margins merge so they take up the same space. If the sizes differ, the resulting size is the size of the largest one.
    Content
    Content
    Vertical paddings don't. The resulting space is the sum of both paddings.
    Content
    Content
    And neither do margins merge with paddings.
    Content
    Content
  5. Margin is conceptually not part of the element. If you have a background, it gets applied to the padding, but not to the margin.
    Content
    Content
    And the position of the background is relative to the outer edges of the padding. "no-repeat 0 0" puts the background image at the top left corner of the padding. (It's the same with repeating background images, but having only one image makes it easier to see in the example.)
    Content
    Ditto for absolutely positioned children in a positioned parent. "top:0; left:0" puts them in the same top left corner.
    Content
  6. If you have a border, the margin is on the outside of the border, the padding inside.
    Content
  7. Borders do not collapse. Two adjacent borders take up both widths. (Note that the possibility exists to have collapsable borders inside tables, but that's outside the scope of this document.)
    Content
    Content
    Nor do they interact with the margin. Margins behave the same way with borders present as they do without.
    Content
    Content
  8. And borders do not have an effect on the position of the background image either (nor on absolutely positioned children in relatively positioned blocks). Non-repeating background image:
    Content
    With repeating background images however, there's a twist. It may look at first like the background is confined to the inside of the border
    Content
    But if you make the border partially transparent (by reducing its opacity or giving it a border-style of dotted or dashed) you'll see that the background will continue under the border!
    Content