Start learning free

LESSON 17 OF 161 · FRONTEND: CSS

Which Rule Is Stronger in JavaScript

Practice

Order only decides between selectors of equal strength. Every selector has a strength, called its specificity: an id like #lamp beats any number of classes, and a class beats any number of tags. A stronger selector wins wherever it sits in the file.

Classes written together with no space match one element that has all of them, and their strength adds up. Here .btn.primary (two classes) beats .btn (one class), even though .btn comes later:

.btn.primary {
  color: white;
}

.btn {
  color: black;
}

A button with class="btn primary" gets white. You could also force a declaration with !important, but then the next change needs another !important. Adding a class to the selector keeps the file easy to follow.

Right now the check prints #222 <- .card for the mug and the notebook and #c60 <- .sale for the lamp. When you're done, it must print:

> the style of .card (3 elements, window 1024 px wide)
  li#mug.card "Mug $12 Buy"
    color: #222   <- .card
  li#notebook.card.sold-out "Notebook Out of stock $7 Buy"
    color: #999   <- .card.sold-out
  li#lamp.card.sale "Lamp Sale $29 Buy"
    color: #080   <- #lamp

Your task: at the end of the file, add an li rule with color: #555 and see that it loses. Then, above the first .card rule, add a #lamp rule with color: #080 and a .card.sold-out rule with color: #999. No !important.


Assignment
Follow the Coding Tutorial to add a tag rule that loses, and an id rule and a two-class rule that win although they come earlier in the file.


Hint
Compare ids first, then classes, then tags. The order in the file matters only when those counts are equal.


STEP 1 OF 6
    Ctrl + Enter to check

    Css Specificity in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free