Web Analytics

Padding & Margin

Beginner ~9 min read

Padding vs Margin

Padding is space inside the element, between content and border.
Margin is space outside the element, between the border and other elements.

HTML
CSS
JS

Padding Shorthand

The padding property can take 1, 2, 3, or 4 values:

  • padding: 20px; - All sides
  • padding: 10px 20px; - Top/Bottom, Left/Right
  • padding: 10px 20px 15px; - Top, Left/Right, Bottom
  • padding: 10px 20px 15px 25px; - Top, Right, Bottom, Left (clockwise)
HTML
CSS
JS

Margin Shorthand

Margin uses the same shorthand syntax as padding. It creates space between elements.

HTML
CSS
JS

Individual Sides

You can also set padding and margin for individual sides using specific properties.

HTML
CSS
JS

Centering with Margin Auto

Use margin: 0 auto; to horizontally center a block element with a defined width.

HTML
CSS
JS
Remember: Padding adds to the element's size (unless using border-box), while margin creates space between elements without affecting size.

Negative Margins

You can use negative margins to pull elements closer or overlap them. Use carefully!

HTML
CSS
JS

Key Points

  • Padding - Space inside, between content and border
  • Margin - Space outside, between elements
  • Both use same shorthand syntax (1-4 values)
  • margin: 0 auto; centers block elements
  • Negative margins pull elements closer
  • Individual properties: padding-top, margin-left, etc.

Quick Quiz

How do you horizontally center a block element?

A
padding: 0 auto;
B
margin: 0 auto;
C
text-align: center;
D
align: center;