Control priority with layers

A third-party rule has an id selector in it. Beat it without !important, and without raising your own specificity.

What to build

A stylesheet organised into layers.

Requirements

  • A statement declares the layers in the order vendor, components.
  • The rule #app .button { color: crimson; } goes in the vendor layer.
  • .button { color: teal; } goes in the components layer, and it has to win.
  • Inside the .button rule, use nesting to add &:hover { color: navy; }.

Constraints

Do not use !important, and do not add an id to your own selector.

Example

The lesson's example has exactly this shape.

Why it works

Layer order is compared before specificity, so a later layer beats any selector in an earlier one, however strong.

Hints

Hint 1

The first @layer statement sets the order, from weakest to strongest.

Hint 2

Layers are compared before specificity.

Hint 3

Nesting a rule inside another uses &.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Layers</title>
  <style>
    @layer vendor, components;
    @layer vendor {
      #app .button { color: crimson; }
    }
    @layer components {
      .button {
        color: teal;
        &:hover { color: navy; }
      }
    }
  </style>
</head>
<body>
  <div id="app"><button class="button">Save</button></div>
</body>
</html>

Lesson: Keeping CSS maintainable →