Spacing and sizing
Understand margin, padding, box-sizing and units so your boxes end up the size you expect.
- 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
- 1Add padding to a card and watch the content move away from its edges.
- 2Add margin and watch the card push neighbouring elements away.
- 3Set box-sizing: border-box and give the card a fixed width together with padding.
- 4Add a max-width to keep the card from growing too wide on a big screen.
* {
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.
Size a card that stays readable
Style a card with comfortable padding and a maximum width so it does not stretch too wide.
.card {
padding: 1rem;
}With box-sizing: border-box, what does a width of 20rem include?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.