CSS Specificity

Specificity is the scoring system browsers use to decide which conflicting CSS rule applies to an element.

When two or more rules set the same property on the same element, the browser does not simply pick the last one. It first compares how specific each selector is, and only falls back to source order when the specificity is a tie.

How Specificity Is Measured

Think of specificity as three counters, usually written as (a, b, c). You count the ids in the selector, then the classes, attributes, and pseudo-classes, then the element names and pseudo-elements. A larger value in a more important column always wins.

Selector pieceColumn it adds to
#menu (an id)a - ids
.active or :hover (class / pseudo-class)b - classes
[type="text"] (attribute)b - classes
p or ::before (element / pseudo-element)c - elements
* (universal selector)adds nothing

A Conflict Example

The id selector wins

<!DOCTYPE html>
<html>
<head>
<style>
/* specificity (1, 0, 1) */
#main p {
  color: red;
}

/* specificity (0, 0, 1) */
p {
  color: blue;
}
</style>
</head>
<body>

<div id="main">
  <p>This paragraph is styled by two rules.</p>
</div>

</body>
</html>

Both rules target the same paragraph, but <code>#main p</code> includes an id, so its color of red is applied even though the plain <code>p</code> rule appears later in the file.

When Specificity Ties

Later rule wins on a tie

<!DOCTYPE html>
<html>
<head>
<style>
.btn {
  background: #00643c;
}

.btn {
  background: #0a7d4e;
}
</style>
</head>
<body>

<button class="btn">Click me</button>

</body>
</html>
Note: Prefer a single well-named class over long, deeply nested selectors. Flat, low-specificity rules are far easier to override later. See also Specificity Hierarchy.

Exercise: CSS Specificity

Which selector has higher specificity: a class selector or an element (type) selector?