Modern CSS Best Practices

Chapter 2 · Practice 3 of 4

Know the two layer rules that surprise people: unlayered styles and !important

From The cascade, specificity and cascade layers

Why it matters

Two behaviours from the cascade layers spec catch most people out. MDN describes both:

1. Unlayered styles beat all layered styles. For normal declarations, any rule not in a layer wins over every layered rule, even one with higher specificity or that comes later. If you adopt layers in an existing project, old unlayered CSS will override your new layered CSS until you move it into a layer.

2. !important reverses the layer order. For important declarations, earlier layers win, and unlayered important styles have the lowest priority among important declarations. This lets a reset layer protect a rule with !important that later layers cannot override.

DeclarationWho wins
NormalUnlayered, then the last declared layer
!importantThe first declared layer, then later layers, then unlayered

Use !important almost never. When you do, use it on purpose in an early layer, such as a utility that must never be overridden.

Example

CSS
@layer base, components;

@layer components {
  .title { color: crimson; }
}

/* Unlayered: wins over .title above, despite equal specificity */
h1 { color: black; }