Differences in behaviour between padding and margin
and border, for good measure.
-
An element can have a margin, which is some space around the element
-
or a padding, which is also space around the element.
-
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.
- 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.
Vertical paddings don't. The resulting space is the sum of both paddings.
And neither do margins merge with paddings.
- Margin is conceptually not part of the element. If you have a background, it gets applied to the padding, but not to the margin.
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.)
Ditto for absolutely positioned children in a positioned parent. "top:0; left:0" puts them in the same top left corner.
- If you have a border, the margin is on the outside of the border, the padding inside.
- 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.)
Nor do they interact with the margin. Margins behave the same way with borders present as they do without.
- 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:
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
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!