Learning on Web Dev Open is free for all.

Take It Apart > The cascade, specificity and inheritanceLayers for a stylesheet you inherited
Phase 01The cascade, specificity and inheritance49 of 434

Layers for a stylesheet you inherited

Someone else wrote 2,000 lines of CSS with ids and !important throughout. @layer is how you get control back without rewriting it.

Build28 minAI implements

Fork the starter. It is a page using a third-party CSS framework plus a local stylesheet, and the local stylesheet is losing fights it should win. There are eleven !important declarations in it, all added by a previous developer who was in a hurry.

The goal: remove all eleven, and have the page look identical, using layers instead.

Declare your order first, at the top of the file, before any rules: @layer reset, vendor, base, components, utilities;. That single line establishes precedence for the whole document, and it is useful to understand what it buys, precedence is now decided by which layer a rule is in, not by how specific it is. A one-class rule in utilities beats a five-selector rule in vendor. That is the point.

Wrap the third-party framework in @layer vendor by importing it with @import url(...) layer(vendor);. Put your own resets in reset, element defaults in base, component styles in components, and single-purpose overrides in utilities. Then delete the !importants one at a time, checking the page after each.

Now learn the rule that catches everyone: unlayered styles beat all layered styles. Anything you leave outside a layer sits above the entire stack. This is occasionally useful as an escape hatch and much more often an accident, a stray rule at the bottom of a file that you forgot to wrap, silently outranking a system you carefully designed. When a layer system "does not work", this is nearly always why.

Finish by writing three lines at the top of the stylesheet explaining the layer order to the next person. The order is a design decision and it is invisible unless someone writes it down.

Done when

  • All eleven !important declarations removed
  • The page visually identical to the original, checked side by side
  • An explicit @layer order declaration at the top of the file
  • The third-party framework imported into its own layer
  • A comment explaining the order, and no unlayered rules left by accident

Nobody marks this for you. It goes into your phase checkpoint, where a person does.

Build this in your own editor

This one runs on your machine rather than in the browser workbench. Work to the outcomes below, then come back and mark it complete.

You should now be able to

  • Organise a stylesheet into cascade layers
  • Override third-party CSS without an escalation war
  • Explain why unlayered styles beat layered ones
Ask the community

Loading…