Start learning free

LESSON 16 OF 161 · FRONTEND: CSS

Two Rules, One Element in JavaScript

Practice

One element often matches several rules. When two of them set the same property, the browser has to pick one value. The rules that decide are called the cascade.

If the two selectors are equally strong, for example one class each, the declaration written later in the file wins. Only the clashing property is decided this way: other declarations from both rules still apply.

.note {
  color: navy;
}

.warning {
  color: red;
}

An element with class="note warning" gets red: both rules set color, both are one class, and .warning comes later. Swap the two rules and it gets navy. Writing the same selector twice works the same way: the later rule wins.

All three products have the class card; the lamp also has sale. The check prints each card's color and the rule it comes from:

> 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: #222   <- .card
  li#lamp.card.sale "Lamp Sale $29 Buy"
    color: #c60   <- .sale

Your task: below the .products > li rule, write a .card rule with color: #333, then a second .card rule with color: #222, then a .sale rule with color: #c60.


Assignment
Follow the Coding Tutorial to write three rules that set color on the cards, and watch the later one win each time.


Hint
The browser keeps both .card rules: the later one wins on every card. .sale is just as strong and comes after them, so it wins on the lamp.


STEP 1 OF 6
    Ctrl + Enter to check

    Css Cascade Order 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