Chapter 03 of 09Part 1 · The page

The cascade and the CSS box model

How CSS decides which rule wins, and how big every box really is once padding, border and margin are added.

11 minBy Zuzo StudioUpdated

10 min

In this chapter you will

  • work out which of two competing CSS rules wins, and why
  • calculate the rendered width of a box with and without border-box
  • give your project page its first stylesheet

Before you startThis builds on Semantic HTML: structure that means something.

Check your understanding

3 questions

Q1A link is styled by #contact a { color: red } and by .footer nav a { color: blue }, and both match. What colour is it?

Show the answer

Red, because the ID gives the first selector more weight The first weighs (1, 0, 1) and the second (0, 1, 2). Specificity is compared column by column from the left, and one ID beats any number of classes.

Q2A box has width: 200px, padding: 20px and a 5px border, with the default box-sizing. How wide is it on screen, not counting margin?

Show the answer

250px 200 for the content, plus 40 for the padding on both sides, plus 10 for the border on both sides.

Q3A heading has margin-bottom: 40px and the paragraph after it has margin-top: 24px. How big is the gap between them?

Show the answer

40px The two margins collapse and the larger one is used, so the gap is 40px.

Key takeaways

  1. The cascade settles conflicts by origin and importance first, then specificity, then order of appearance.
  2. Specificity is compared as IDs, then classes, then elements, so one ID beats any number of classes.
  3. Every box is content, padding, border and margin, and by default width sets only the content.
  4. box-sizing: border-box makes width include padding and border, which is why most sites set it on every element.
  5. Low, even specificity and named custom properties keep a stylesheet easy to change.
Up next · Chapter 04 · 11 min Flexbox vs grid: laying out a page Flexbox lines things up in a row or a column, grid draws rows and columns at once. Learn when to use each.

02FAQ

Questions on this chapter

Something else on your mind? Email the studio and a designer, not a salesperson, replies within a day.

What is the CSS box model?

The CSS box model describes every element as a rectangle made of four layers: the content, the padding around it, the border, and the margin outside the border. Together they decide how much space the element takes up on the page.

What is the difference between padding and margin?

Padding is space inside the border and shows the element's background. Margin is space outside the border, always transparent, and pushes neighbouring elements away. Vertical margins between blocks can collapse into one, padding never does.