When Rules Clash · CSS

Ch 1 · Styling Basics — card 3 of 3.

What happens when two rules try to set the same property on one element? CSS settles it with the cascade, a set of tie-break rules. Knowing them saves a lot of confusion when a style seems to refuse to work.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My Page</title>
    <style>
      .note { color: #1e3a8a; font-family: Georgia, serif; }
      p { color: green; }
      p { color: #0f766e; }
      .urgent { color: #dc2626; }
    </style>
  </head>
  <body>
    <div class="note">
      <h2>Reminder</h2>
      <p>PE kit on Friday.</p>
      <p class="urgent">Bring trainers!</p>
    </div>
  </body>
</html>

The two p rules have equal strength, so the one lower down wins and paragraphs turn teal. The .urgent paragraph is red, because a class selector is more specific than a tag, whatever the order. The heading has no rule of its own, so it inherits the colour and font from .note, its parent. Text properties such as color and font-family are inherited; box properties such as border are not.