Skip to content
Visual explainer 5h to learn 5 steps

Selectors, cascade, box model & units

Predict which rule wins and size elements without fighting the box model.

By Invicly Tech, , in Frontend with React & Next.js. About 9 minutes to read.

Topic 2 of 36

In short

CSS applies styles through selectors, and the cascade decides which rule wins when several match. The box model defines how content, padding, border and margin add up to an element's size.

Explained simply

CSS is the language that styles HTML: colors, sizes, spacing and layout. A CSS rule has two parts. The selector picks which elements to style, like .card or h2. The declarations say what to change, like color: navy.

Often several rules target the same element and disagree. One says the text is blue, another says red. The cascade is the set of rules the browser uses to pick a winner. Once you know how it decides, CSS stops feeling random.

Every element is drawn as a box. The box has content in the middle, then padding (space inside the border), then the border, then margin (space outside, pushing other boxes away). Most layout bugs come from forgetting that padding and border add to the size.

Units are how you say how big things are. px is a fixed size. rem follows the user's chosen font size, so text grows if someone sets a larger default. % is relative to the parent. Picking the right unit makes pages that adapt instead of break.

Press Play on a diagram to walk through it one step at a time.

LayersThe box model, outside in
  1. 1
    Margin

    Transparent space outside the border, separating elements

  2. 2
    Border

    The visible edge around padding and content

  3. 3
    Padding

    Space between the border and the content

  4. 4
    Content

    Text and children; width applies here by default

FlowHow the cascade picks a winner
  1. Step 1
    Origin & importance

    Author styles beat browser defaults; !important flips the order

  2. Step 2
    Specificity

    IDs beat classes, classes beat element selectors

  3. Step 3
    Source order

    With equal specificity, the later rule wins

  4. Step 4
    Inheritance

    Unset properties like color may inherit from the parent

LayersThe box model, outside in
  1. 1
    Margin

    Transparent space that pushes neighbours away

  2. 2
    Border

    The visible edge, counts toward size

  3. 3
    Padding

    Space inside the border, shows the background

  4. 4
    Content

    Text and children; width applies here in content-box

MapSpecificity of common selectors
Selector score (IDs, classes, types)
  • (1,0,0) and up
    • #header
    • #nav a
  • (0,1,0) to (0,3,0)
    • .btn
    • a:hover
    • input[type="email"]
    • .menu .item:hover
  • (0,0,1) to (0,0,2)
    • p
    • ul li
  • (0,0,0)
    • * universal
    • :where(.card)

In depth

How the cascade really decides

When two declarations set the same property on the same element, the browser checks a list of tie-breakers in order and stops at the first one that differs.

First comes origin and importance: your styles beat browser defaults, and !important flips the order. Next come cascade layers (@layer), if you use them. Then specificity: the more precise selector wins. Last is source order: if everything else ties, the rule written later wins.

Inheritance is a separate idea. Some properties, like color and font-family, flow down from parent to child when the child has no value of its own. Others, like border and padding, do not inherit.

  • 1. Origin and !important
  • 2. Cascade layers
  • 3. Specificity
  • 4. Order in the source
  • Inheritance only fills gaps

Counting specificity

Specificity is written as three numbers: (IDs, classes, types). Count each part of the selector. #nav a is (1, 0, 1). .menu .item:hover is (0, 3, 0), because pseudo-classes like :hover and attribute selectors like [type] count as classes. ul li is (0, 0, 2).

Compare the numbers left to right. Any ID beats any number of classes, and one class beats any number of types. Inline style attributes beat all selectors. The :where() function adds zero specificity, which is handy for easy-to-override defaults.

A good habit is to style mostly with single classes. Then specificity stays flat and source order does the rest.

content-box vs border-box

By default, width sets only the content area (box-sizing: content-box). A 300px wide box with 20px padding and a 2px border actually takes 344px. That is why two 50% columns with padding wrap onto two lines.

With box-sizing: border-box, width includes padding and border, so 300px means 300px. Most projects set it on every element at the start of the stylesheet. Margin is never part of the width in either mode.

Comparewidth: 300px, 20px padding, 2px border
content-box (default)
  • width sets the content only
  • 300 + 40 padding + 4 border
  • Box takes 344px
  • Margin is extra
border-box
  • width includes padding and border
  • Box takes 300px
  • Content shrinks to 256px
  • Margin is extra

Choosing units

Use rem for font sizes and most spacing. 1rem equals the root font size, usually 16px, and it grows when a user raises the default size in browser settings. em is relative to the current element's font size, which is handy for padding on a button that should scale with its text but can compound when nested.

Use % or fr for widths inside layouts, vw and vh for viewport-based sizes, and px for hairline details like a 1px border.

  • rem: fonts and spacing
  • em: sizes that follow the element's own text
  • %: relative to the parent
  • px: borders and tiny fixed details

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Write type, class and attribute selectors~1h
  2. 2
    Predict specificity and cascade order~1h
  3. 3
    Apply box-sizing: border-box~1h
  4. 4
    Choose between px, rem, em and %~1h
  5. 5
    Debug styles in DevTools~1h

Key points

  • Specificity is compared as IDs, then classes and attributes, then element selectors.
  • Set box-sizing: border-box so width includes padding and border.
  • Use rem for font sizes and spacing so layouts respect user font settings.
  • DevTools shows every matching rule and crosses out the ones that lost.

Key terms

Tap a card to flip it. 0/5 known

Examples

css
*, *::before, *::after {
  box-sizing: border-box;
}

.card {
  width: 20rem;
  padding: 1rem;
  border: 1px solid #ddd;
  margin-block: 1.5rem;
}

.card h2 { font-size: 1.25rem; }
.card[data-featured] { border-color: gold; }

border-box reset, rem units, and class plus attribute selectors.

Why is my button still grey?

You write .primary { background: blue; } but the button stays grey. Step 1: inspect it in DevTools; the Styles pane shows .primary crossed out. Step 2: the winning rule is .toolbar button { background: grey; }, score (0,1,1). Step 3: your rule is (0,1,0), so it loses. Fix: raise it to the same weight and place it later, or better, give the button one class and remove the nested toolbar rule so both are single classes.

css
.toolbar button { background: grey; }   /* (0,1,1) wins */
.primary { background: blue; }          /* (0,1,0) loses */

/* Fix: equal weight, written later */
.toolbar .primary { background: blue; } /* (0,2,0) */

Two columns that refuse to sit side by side

Two cards each have width: 50% and padding: 1rem. On screen, the second card drops below the first. Step 1: in content-box mode each card is 50% plus 2rem, so together they exceed 100%. Step 2: add the border-box reset. Step 3: now padding is inside the 50% and both fit. This reset is the first rule in almost every modern stylesheet.

css
*, *::before, *::after {
  box-sizing: border-box;
}
.card {
  width: 50%;
  padding: 1rem;
  float: left; /* or put both in a flex container */
}

Quick reference

  • Cascade order: importance > layers > specificity > source order
  • Specificity (IDs, classes, types); compare left to right
  • Pseudo-classes and [attributes] count as classes; ::before counts as a type
  • *, *::before, *::after { box-sizing: border-box; }
  • 1rem = root font size (16px by default)
  • Vertical margins between blocks collapse: 20px + 30px gives 30px
  • Use :where() for zero-specificity defaults
  • Avoid !important except for small utility overrides

Common mistakes

  • Reaching for !important instead of fixing specificity.
  • Forgetting border-box, so padding makes boxes wider than expected.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the specificity of .nav a:hover?

Question 2

2Two rules have identical specificity. Which wins?

Question 3

3With box-sizing: border-box, a box has width 200px, padding 10px and border 2px. How wide is it on screen?

Question 4

4Why prefer rem over px for font sizes?

Question 5

5Which property is inherited by default?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write the specificity of each selector: (a) #main p, (b) .card .title, (c) a[href^="http"], (d) li:first-child.

  2. Exercise 2medium

    Create a .btn class whose padding grows with its own font size, and a .btn-lg variant that only changes the font size.

  3. Exercise 3hard

    A third-party widget sets .widget .title { color: red; }. You want your theme's titles to override it without !important or IDs, and still let later utilities override yours. Use cascade layers.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why does my margin-top leak out of the parent?
That is margin collapsing: a child's top margin can merge with its parent's when nothing separates them. Add padding or a border to the parent, or make it a flex or grid container.
Is using IDs for styling bad?
IDs work, but their high specificity makes them hard to override later. Use IDs for links and JavaScript hooks, and classes for styling.
What is the difference between rem and em?
rem is relative to the root html font size, so it is the same everywhere. em is relative to the current element's font size, so it changes when nested inside bigger or smaller text.

Go deeper

ShareXLinkedInWhatsApp