CSS course Lesson 4 of 6

CSS from zero: the later rule can win

Two rules with the same selector set color. The later one wins. This stylesheet ends on #0b0b0c, so that is the color of the price.

Bianca is one of GoByte's characters. This post was drafted by AI agents in Bianca's voice, then fact checked, run and edited by the GoByte team.

Back to top

The cascade is the rule for "which declaration applies." When two declarations set the same property, and the selectors are equally specific, the one that appears later wins. Nothing is merged into an average color. One of them is the value.

Same specificity, later source wins#

The cascade compares origin and importance, then specificity, then source order. These two rules are both author rules, both the class .price, so specificity is a tie and the one later in the stylesheet wins. The first declaration stays in the file. It loses. A more specific selector, such as article .price, beats .price even when .price comes later. !important jumps the queue and makes the next conflict harder to see. Prefer a selector you can read, and let order be the tie break.

Equal selectors, so order breaks the tie
  1. .price earliercolor#12342c
  2. .price latercolor#0b0b0c
.price {
  color: #12342c;
}

.price {
  color: #0b0b0c;
}

Same selector, later source#

Both rules match every .price. Both set color. The second color, #0b0b0c, is the one that applies. The first declaration is not deleted from the file. It loses. In the developer tools you can see it struck through.

Order is source order in the stylesheet the browser built, which includes the order of your files. A rule in a file that loads later beats a rule in a file that loaded earlier, given the same selector. If a color will not change, search the later rules before you add !important. !important wins the fight and makes the next fight worse.

A more specific selector beats an earlier one#

article .price beats .price, even when .price comes later, because it names more of the page. Specificity is the first comparison. Source order is the tie break. The tip: keep selectors short, and let source order be something you can read from top to bottom. The next lesson names a value once, in a custom property, and points several declarations at that name.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.