CodeBlanks Logo Icon CodeBlanks

Spacing and alignment

CSS course · Beginner · Lesson 18/82

Add spacing with margin and padding, and align content.

Spacing and alignment

In this lesson you'll set the outer space, inner space, and alignment of paragraphs. margin sets space outside the element border, padding sets space inside it. text-align aligns text horizontally.

The two-value shorthand is common: margin: 12px 0 sets vertical and horizontal space separately. text-align: left aligns text left, center centers it, right aligns it right. These three properties make the page breathe and look tidy.

Box model: margin vs padding

Every HTML element is treated as a box. margin controls space outside the box, padding controls space between the content and the border. Both make the page breathe but in different places.

Example: p { margin: 12px 0; padding: 0 16px; }. This rule leaves 12 pixels above and below each paragraph, and gives inner space on the left and right. The result: paragraphs don't stick together and don't touch the line edges.

Exercise Add the p rule

Take the file from the previous lesson (header comment + body and h1 rules). Below it, add a p type selector rule with these declarations: margin: 12px 0, padding: 0 16px, text-align: left. End each declaration with a semicolon.

Show example solution
/* Personal Site stylesheet */

body {
  margin: 0;
}

h1 {
  color: #2a3d66;
  font-family: Georgia, serif;
  font-size: 2rem;
}

p {
  margin: 12px 0;
  padding: 0 16px;
  text-align: left;
}

Test yourself

  1. What does body { margin: 0; } do?

    body {
      margin: 0;
    }
    • Changes the background color
    • Sets the typeface
    • Centers the text
    • Resets the browser's default outer spacing
    Show answer

    Resets the browser's default outer spacing — Correct. margin: 0 removes body's default outer space; content reaches the browser edge.

  2. Complete the paragraph alignment

    p {
      text-align: ____;
    }
    Show answer
    p {
      text-align: left;
    }
  3. Match each property to its meaning

    margin
    outer space
    padding
    inner space
    text-align
    horizontal alignment
    color
    text color

All lessons in Beginner