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]

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 {padding: 1rem 2rem 3rem 4rem}

is a shorthand to the following:

div
{
padding-top: 1rem;
padding-right: 2rem;
padding-bottom: 3rem;
padding-left: 4rem;
}

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 {margin: 1rem 2rem 3rem 4rem}

is equivalent to the following:

div
{
margin-top: 1rem;
margin-right: 2rem;
margin-bottom: 3rem;
margin-left: 4rem;
}

Margin can be negative.

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

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

CSS

Basics

Color

Font

Box Model

Layout

Transform/Animation

Line Wrap, Justification

Box Decoration

Misc