Naar hoofdinhoud
Frontend is een gratis bonus op CodeMentor AI — het hoofdproduct is Python. Registreer om je voortgang op te slaan en alle 299 Frontend-lessen + 1,100+ Python-lessen te ontgrendelen.Meld je aan — gratis
← 🎨 CSS as a design system·Module B1 · Les 2
OpdrachtTwo rules style the same paragraph. The more-specific rule should win. .alert sets color to red. p sets color to blue. The p says 'Disk almost full' and has class='alert'. Add CSS so .alert (red) beats p (blue). Then add a SECOND rule .container .alert that sets color to #C00 (darker red).

Specificiteit: geteld, niet gevibreerd

100 XP9 minFREE
Theorie

When two selectors target the same element

Whichever has higher specificity wins. Specificity is a 4-part score:

(inline, IDs, classes/attrs/pseudo-classes, elements/pseudo-elements)

Read left-to-right; the first non-equal column decides. Each column is just a count.

button                        → (0, 0, 0, 1)
.cta                          → (0, 0, 1, 0)
.cta:hover                    → (0, 0, 2, 0)   /* :hover is a pseudo-class */
#main button.cta              → (0, 1, 1, 1)
.parent .cta                  → (0, 0, 2, 0)

#main button.cta beats .cta:hover because column 2 (IDs) is 1 vs 0 — and ID wins even though :hover had more class-level pieces.

When specificity ties

The later rule in source order wins. So if two rules with identical specificity target the same element, last one written wins.

Inline is a separate origin, not a specificity row

<p class="alert" style="color: red">…</p>

You'll see older articles write style="" as specificity (1, 0, 0, 0) and call inline "the highest row". The modern CSS Cascade spec treats inline styles as part of the author origin, but with their own precedence step that is checked before layers and specificity — so they win against any normal author selector regardless of how many IDs you stack. Practical takeaway is the same — inline beats #a #b #c — but the *reason* on an interview question is "element-attached styles have their own cascade step", not "row 1 specificity". A normal inline declaration loses to an !important declaration from a stylesheet (next lesson).

Calculate this in your head

For section#main article.post.featured h2:first-of-type:

  • IDs: 1 (#main)
  • Classes/attrs/pseudo-classes: 3 (.post, .featured, :first-of-type)
  • Elements: 3 (section, article, h2)
  • Score: (0, 1, 3, 3)

Compare to .featured alone = (0, 0, 1, 0). The first wins by a mile (ID column 1 vs 0).

The lesson

Don't reach for !important to win a fight. Increase your specificity by one class level, or rewrite to use the same level as the rule you're trying to override.

2 tabs
Live preview
← VorigeVolgende les →

Eén Python- of web-tip per dag — per e-mail

Kort, met de hand geschreven, geen spam. Met één klik afmelden.