Specificity: Which Style Wins

The previous example is pretty straightforward. But what if the three styles listed in Section 5.1.4 each had a different font specified for the font-family property? Which of the three fonts would a Web browser pay attention to?

As you know if you've been reading carefully so far, the cascade provides a set of rules that helps a Web browser sort out any property conflicts; namely, properties from the most specific style win. But as with the styles listed in Section 5.1.4, sometimes it's not clear which style is most specific. Thankfully, CSS provides a formula for determining a style's specificity that's based on a value assigned to the style's selector—a tag selector, class selector, ID selector, and so on. Here's how the system works:

  • A tag selector is worth 1 point.

  • A class selector is worth 10 points.

  • An ID selector is worth 100 points.

  • An inline style (Section 2.5.1) is worth 1000 points.

The bigger the number, the greater the specificity. So say you create the following three styles:

  • a tag style for the <img> tag ( specificity = 1)

  • a class style named .highlight (specificity = 10)

  • an ID style named #logo (specificity = 100)

Then, say your Web page has this HTML: <img id="logo" class="highlight" src="logo.gif" />. If you define the same property—such as the border property—in all three styles, then the value from the ID style (#logo) always wins out.

Note

A pseudo-element (like :first-child for example) is treated like a tag selector and is worth 1 point. ...

Get CSS: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.