CSS: Margin vs Padding

By Xah Lee. Date: . Last updated: .

What's the difference between CSS's margin and padding?

padding is the area inside the border.

margin is the area outside the border.

border is between margin and padding. [see CSS: Border, Outline]

css padding vs margin
Padding is the area insider the border, margin is the area outside the border. The border here is the black line between yellow and red.

Padding

The code:

div.xyz {padding: 10px 20px 30px 40px}

is a shorthand to the following:

div.xyz
{
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}

Padding cannot be negative.

“padding” can have 1 to 4 values, separated by space:

  1. padding: all_sides
  2. padding: top/bottom left/right
  3. padding: top left/right bottom
  4. padding: top right bottom left

Margin

this code:

div.xyz {margin: 1em 2em 3em 4em}

is equivalent to the following:

div.xyz
{
margin-top: 1em;
margin-right: 2em;
margin-bottom: 3em;
margin-left: 4em;
}

Margin can be negative.

“margin” can have 1 to 4 values, same as padding.

Box Sizing

[see CSS: Box Sizing]

Reference

Box model#propdef-padding

Box model#propdef-border

Box model

Box Model, Width, Padding, Margin, Border

  1. CSS: Margin vs Padding
  2. CSS: Border, Outline
  3. CSS: Box Sizing
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.