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:

Margin

The syntax of margin is same as padding. But margin values can be negative.

Example. This code:

div {margin: 1rem 2rem 3rem 4rem}

Is same as

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

Buy JavaScript in Depth

CSS

Basics

Color

Font

Text Decoration

Box Model

Box Decoration

Layout

Transform/Animation

Line Wrap

Misc