CSS Essentials·CSS without guesswork

Spacing and sizing

Understand margin, padding, box-sizing and units so your boxes end up the size you expect.

Beginner 12 min read Lesson 5 of 480 Challenge included
What you will be able to do
  • Know the difference between padding, which sits inside, and margin, which sits outside.
  • Apply box-sizing: border-box so width and height include padding and border.
  • Use min-width and max-width to stop content from overflowing or shrinking too far.
  • Choose rem for scalable spacing and px only where a size must stay fixed.

In plain English

Padding is space inside an element, between its content and its border, while margin is space outside the element that pushes neighbours away. The box-sizing: border-box rule makes width and height include padding and border, so a box stays the size you say. Width plus min-width and max-width control how an element stretches, and units change how sizing scales: px is fixed, rem follows the root font size, and em follows the current element font size.

Step by step

  1. 1Add padding to a card and watch the content move away from its edges.
  2. 2Add margin and watch the card push neighbouring elements away.
  3. 3Set box-sizing: border-box and give the card a fixed width together with padding.
  4. 4Add a max-width to keep the card from growing too wide on a big screen.
spacing.cssCSS
* {
  box-sizing: border-box;
}

.card {
  width: 100%;
  max-width: 40rem;
  padding: 1.5rem;
  margin: 2rem auto;
}

.card h2 {
  margin-top: 0;
  font-size: 1.5rem;
}

.badge {
  font-size: 0.75em;
  padding: 0.5em 1em;
}

Common mistakes

  • Beginners often use margin when they mean padding and then wonder why the background colour does not reach the edge.
  • A very common mistake is expecting width to mean the visible size when, by default, padding and border are added on top.
  • Confusing rem and em is easy, and it leads to spacing that scales unpredictably as nesting changes.
  • Forgetting a max-width lets a paragraph stretch across a huge monitor, which is hard to read.
Your turn

Size a card that stays readable

Easy

Style a card with comfortable padding and a maximum width so it does not stretch too wide.

CSS · starter
.card {
  padding: 1rem;
}
Check your understanding before moving on.
Knowledge checkQuestion 1

With box-sizing: border-box, what does a width of 20rem include?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Focus and accessibility
Lesson 5 of 480 · 0% of course