Sub topic 7
Specificity and why inline styles usually win
This chapter assumes you can write a basic CSS rule, you know the three ways to attach CSS (the style attribute, the style element, and a linked stylesheet), and you can open browser developer tools. Earlier chapters covered how source order settles ties. Here you learn what happens when source order is not the deciding factor.
The problem specificity solves
A single element often matches several rules that set the same property. Consider this paragraph:
<p id="intro" class="note">Hello</p>A rule for p, a rule for .note, and a rule for #intro can all set color. The browser needs one answer. It does not simply pick the last rule written. It runs a fixed series of comparisons, and the later rule wins only if everything earlier in the series is tied.
The series, from strongest to weakest, is:
- Importance: declarations marked
!importantbeat normal ones. - Inline versus selector: for declarations of the same importance, a declaration in a
styleattribute beats declarations from rules with selectors. - Specificity: a measure of how precisely a selector targets the element. Higher specificity wins.
- Source order: if all else is tied, the declaration that comes later wins.
This is a simplified view. It leaves out origins (browser defaults, user styles, author styles) and cascade layers. For ordinary page authoring it covers the cases you will meet.
How specificity is calculated
A selector's specificity is three counts, written as a triple. The parts are always compared in this order:
- A: the number of ID selectors (
#intro). - B: the number of class selectors (
.note), attribute selectors ([type="text"]), and pseudo-classes (:hover,:first-child). - C: the number of type selectors (
p,a) and pseudo-elements (::before,::first-line).
The universal selector * and combinators (>, +, ~, and the descendant space) add nothing.
| Selector | Score (A,B,C) | Reason |
|---|---|---|
| `*` | 0,0,0 | The universal selector counts for nothing. |
| `p` | 0,0,1 | One type selector. |
| `.note` | 0,1,0 | One class. |
| `p.note` | 0,1,1 | One class and one type. |
| `nav a:hover` | 0,1,2 | One pseudo-class, two types. |
| `a[href^="https"]` | 0,1,1 | One attribute selector, one type. |
| `#intro` | 1,0,0 | One ID. |
| `p::first-line` | 0,0,2 | A type and a pseudo-element. |
| `:where(.a, .b) p` | 0,0,1 | `:where()` always contributes zero. |
| `:is(#a, .b) p` | 1,0,1 | `:is()` takes its most specific argument. |
Compare left to right, not as one number
The triples are compared one position at a time. A beats B, and B beats C, regardless of the counts. A selector with one ID (1,0,0) beats a selector with a hundred classes (0,100,0). Some older tutorials say to read the triple as a number such as 0,1,1 equals 11. That is wrong, because eleven type selectors (0,0,11) never beat a single class (0,1,0).
A worked example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Specificity demo</title>
<style>
#intro { color: orange; }
p.note { color: purple; }
.note { color: green; }
p { color: blue; }
</style>
</head>
<body>
<p id="intro" class="note">Which color am I?</p>
</body>
</html>All four rules match the paragraph. Their scores are 1,0,0, 0,1,1, 0,1,0, and 0,0,1. The ID rule is highest, so the text is orange. Reordering the four rules changes nothing, because the specificity comparison happens before source order. Delete the #intro rule and the text becomes purple, since 0,1,1 beats 0,1,0.
Why inline styles usually win
A declaration in a style attribute is not attached to a selector. The specification treats it as having higher precedence than any selector-based declaration of the same importance. You can think of it as a fourth, leftmost column in the score: (1,0,0,0) for inline, against (0,1,0,0) for an ID rule. Because that column is compared first, no combination of IDs, classes, and types can catch up.
Add an inline style to the earlier paragraph:
<p id="intro" class="note" style="color: red;">Which color am I?</p>The text is now red. The inline declaration wins over #intro, whether the #intro rule sits in a style element, in a linked file, or after the paragraph in the document. Where the other rules live does not matter, because source order is only consulted when specificity is tied.
This also explains a common frustration. If a CMS, an email template, or a script injects style="..." onto an element, your external stylesheet cannot override it with a normal rule, however specific the selector. Your options are to remove the attribute, to change it with JavaScript, or to use !important (covered below).
`!important` reverses the usual order
Adding !important to a declaration lifts it into a higher tier. All important declarations are compared against each other first, and normal declarations are only compared when no important one is in play.
<head>
<style>
p.note { color: purple !important; }
</style>
</head>
<body>
<p class="note" style="color: red;">Purple, not red.</p>
<p class="note" style="color: red !important;">Red: both are important, so the inline one wins.</p>
</body>In the first paragraph, the important declaration from the selector rule beats the normal inline declaration. In the second, both are important, so the normal rule applies within that tier and the inline declaration wins.
The practical rules are:
- An important selector rule beats a normal inline style.
- An important inline style beats an important selector rule.
- Between two important selector rules, specificity and then source order decide.
Cases where specificity does not apply
Inheritance always loses to a direct rule
Some properties, such as color and font-family, are inherited from the parent element. An inherited value has no specificity at all. Any rule that targets the element itself beats it, even a rule with a score of 0,0,0.
<style>
#card { color: crimson; }
p { color: black; }
</style>
<div id="card">
<p>I am black.</p>
</div>The #card rule has high specificity, but it targets the div. The paragraph inherits crimson from the div only if nothing targets the paragraph directly. The p rule does target it, so the paragraph is black. Many "my high-specificity rule is ignored" bugs come from this.
Position and file of origin do not add weight
A rule in a linked stylesheet and a rule in a style element have exactly the same standing. Only source order separates them, and that is only consulted on a tie. A linked file placed after a style element can override it, and one placed before cannot, if the specificity is equal.
Cascade layers and `:where()`
Modern CSS lets you lower the cost of specificity on purpose. A selector wrapped in :where() contributes zero, which is useful for defaults that you want anything to override. Cascade layers (@layer) add a step before specificity: for normal declarations, a rule outside any layer beats a rule inside a layer, whatever their specificity. Inline styles still beat both. You do not need either feature to follow this chapter, but you should know they exist when you meet a stylesheet that uses them.
Common errors and how to diagnose them
| Symptom | Likely cause | Fix |
|---|---|---|
| A new rule has no effect | A rule with higher specificity sets the same property | Inspect the element and compare scores. Raise the new selector's specificity or lower the old one. |
| Rule works in the `style` element but not in the linked file | The link comes before the `style` element and scores are tied, or an inline style is present | Check source order, then look for a `style` attribute. |
| Rule is overridden by an inline style | The `style` attribute outranks all normal selector rules | Remove the attribute, or use `!important` as a last resort. |
| Changing a parent's style does nothing for a child | A direct rule on the child beats inheritance | Target the child, or remove the conflicting rule. |
| Adding more classes did not beat an ID | A beats B regardless of count | Use an ID in the new selector, or better, avoid IDs in your CSS. |
A habit that prevents most of these is to style with single class selectors (0,1,0) and keep selectors short. When everything has the same low specificity, source order stays predictable, and you rarely need !important.
Where to look when a rule loses
Open the developer tools and select the element. In the styles pane, overridden declarations are shown with a line through them, and the rule that won is listed above. Hovering over a selector typically shows its specificity. The next chapter walks through this in detail. For now, use it to verify the scores you calculate by hand.
Exercise
A paragraph is <p id="msg" class="alert warning"> with no inline style. The page has these rules in this order: .alert.warning { color: red; }, p { color: blue; }, #msg { color: green; }, p.alert { color: black; }. What color is the text, and what are the four scores?
Show answer
The text is green. The scores are .alert.warning = 0,2,0; p = 0,0,1; #msg = 1,0,0; p.alert = 0,1,1. The ID rule has the highest first number, so it wins. Source order is never consulted because no two scores tie at the top.
Exercise
You add style="color: red;" to a paragraph. Your linked stylesheet contains body p.note#intro { color: navy !important; } and the paragraph matches it. What color is the text, and why? What would it be if the inline style were style="color: red !important;"?
Show answer
Navy. Both declarations are not at the same importance: the stylesheet declaration is important and the inline one is normal, so the important tier is compared first and the stylesheet rule wins. With !important on the inline declaration, both are important, so the inline one beats the selector rule and the text is red.
Exercise
A rule .btn { background: gray; } is in a linked stylesheet. A script has added style="background: gold;" to a button with class btn. Name two ways to make the button gray without editing the script.
Show answer
Use !important in the stylesheet, for example .btn { background: gray !important; }, since an important selector rule beats a normal inline declaration. Alternatively, remove or clear the attribute at runtime from other JavaScript, such as button.removeAttribute("style"). Raising the selector's specificity does not work, because inline styles outrank every normal selector.