Sub topic 5
Understand the cascade, specificity and inheritance
This chapter explains how the browser picks a winner when several CSS rules target the same element. It assumes you can write a CSS rule with a selector and declarations, link a stylesheet to an HTML page, and use the browser's developer tools to inspect an element. The examples extend the personal site you have built so far.
Why conflicts happen
A single element often matches many rules. A link in your navigation can match the a rule from your base styles, a nav a rule you wrote for the header, and a browser default rule that underlines links. Each rule may set color or text-decoration differently.
The browser must end up with one value for each property on each element. The process it uses is called the cascade. The cascade is a fixed sequence of tie-breakers. It runs separately for every property on every element.
The main tie-breakers, in order of priority, are:
- Origin and importance: where the rule comes from, and whether it uses
!important. - Specificity: how precisely the selector targets the element.
- Order of appearance: which matching rule comes last.
If a property has no matching rule at all, inheritance or the property's initial value supplies the result.
Origins: who wrote the rule
CSS comes from three main sources, called origins:
- User agent: the browser's built-in stylesheet. It gives headings their size, links their blue color, and
bodyits default margin. - Author: your stylesheets. This is the origin you control.
- User: preferences set by the visitor, such as a larger default font size or a forced high-contrast mode.
For normal declarations, author rules beat user rules, and user rules beat browser defaults. That is why your a { color: ... } rule replaces the default link color without any extra effort.
For declarations marked !important, the order reverses: user-agent and user important rules outrank author important rules. This lets a visitor's accessibility settings override a page's styling when they need to.
Specificity: how precisely a selector aims
When two author rules set the same property and neither is !important, the browser compares the specificity of their selectors. Specificity is a score. A more specific selector wins, whatever its position in the file.
You can read specificity as three counts, written (IDs, classes, types):
| Selector part | Counts as | Examples |
|---|---|---|
| ID selector | IDs | `#about` |
| Class, attribute, pseudo-class | Classes | `.card`, `[href]`, `:focus-visible`, `:hover` |
| Type selector, pseudo-element | Types | `a`, `p`, `::before` |
| Universal selector, combinators | Nothing | `*`, `>`, `+`, a space |
The browser compares the IDs count first. Only if those tie does it compare classes, and only then types. The counts are not added into one number. A selector with one ID beats a selector with any number of classes.
Some worked scores:
| Selector | Score (IDs, classes, types) |
|---|---|
| `a` | (0, 0, 1) |
| `nav a` | (0, 0, 2) |
| `nav a:hover` | (0, 1, 2) |
| `.project-list a` | (0, 1, 1) |
| `#projects .project-list a` | (1, 1, 1) |
| `a[href^="mailto:"]` | (0, 1, 1) |
Inline styles written in a style attribute beat all of these. They are best avoided in your own pages, because they are hard to override and they mix content with presentation.
Two functional pseudo-classes need a special note. :where() always contributes zero specificity. :is() and :not() contribute the specificity of their most specific argument. So :where(nav, footer) a scores (0, 0, 1), while :is(nav, footer) a also scores (0, 0, 2), because the most specific argument is a type selector.
A specificity conflict on your site
Suppose your HTML contains this link:
<section id="contact">
<h2>Contact</h2>
<p><a class="email-link" href="mailto:[email protected]">[email protected]</a></p>
</section>Now consider these rules:
a {
color: #0b5cad;
}
.email-link {
color: #1f2933;
}
#contact a {
color: #8a1c1c;
}All three match the link. The scores are (0, 0, 1), (0, 1, 0) and (1, 0, 1). The ID rule wins, so the link is dark red. The order of the rules in the file does not matter here. If you moved #contact a to the top, it would still win.
This is the usual source of "my style is not applying" problems. A rule you wrote later lost to a rule with a higher score that you forgot about.
Source order: the last rule wins a tie
When specificity is equal, the rule that appears later in the stylesheet wins. This also applies across files: a stylesheet linked later in the <head> overrides an earlier one for equal-specificity conflicts.
a {
color: #0b5cad;
}
a {
color: #6b21a8;
}Both selectors score (0, 0, 1), so links become purple.
A practical consequence is the order of link states. Browsers apply :link, :visited, :hover and :active with equal specificity, so they are decided by order. A common memory aid is "LoVe HAte": link, visited, hover, active.
a:link { color: #0b5cad; }
a:visited { color: #6b21a8; }
a:hover { text-decoration: underline; }
a:active { color: #8a1c1c; }If you put a:hover before a:visited, the visited color overrides the hover rule on visited links, and the hover effect appears broken for them.
Inheritance: values passed down the tree
Some properties pass their computed value from a parent element to its children when no rule sets them directly. This is inheritance.
Properties that inherit by default are mostly related to text:
colorfont-family,font-size,font-weight,font-styleline-heighttext-alignlist-stylevisibility
Properties that do not inherit are mostly related to boxes and layout:
marginandpaddingborderbackgroundwidthandheightdisplay
This is why setting font-family and color on body styles nearly all the text on the page, as in the base stylesheet from the spine. It is also why setting margin: 0 on body does not remove margins from the headings inside it. Margins do not inherit.
An inherited value has no specificity at all. Any rule that directly matches an element beats an inherited value, even a rule with a score of (0, 0, 0), such as * { color: black; }. This surprises many learners. If body has a color and * sets another color, every element receives the * color, because the rule matches each element directly.
Avoid the universal selector for properties that you want to inherit. For box-sizing, which does not inherit by default, the universal selector is a fine choice.
Controlling inheritance with keywords
Four keywords give you explicit control over any property:
| Keyword | Effect |
|---|---|
| `inherit` | Take the parent's computed value, even for a property that does not normally inherit. |
| `initial` | Use the property's specification default. |
| `unset` | Act as `inherit` for inherited properties, and as `initial` for the rest. |
| `revert` | Roll back to the value from the previous origin, usually the browser default. |
A common use of inherit is making form controls and buttons match the page text. Browsers give them their own font by default.
button,
input,
textarea {
font: inherit;
}Another use is links in the footer that should take the footer's text color:
footer a {
color: inherit;
}Using `!important` and avoiding it
Adding !important to a declaration moves it into a higher-priority layer of the cascade, above all normal declarations.
.email-link {
color: #1f2933 !important;
}Now .email-link beats #contact a, even though its specificity is lower. This works, but it creates a new problem. The only way to override an !important declaration is another !important declaration with equal or higher specificity or later order. A stylesheet that uses it casually quickly turns into an arms race.
Reach for these options first:
- Lower the specificity of the rule you want to override, for example by replacing an ID selector with a class.
- Raise the specificity of your new rule a little, for example by adding a class.
- Move the new rule later in the file.
Keep !important for narrow utility rules, such as a .visually-hidden helper, where the rule must win everywhere.
Cascade layers, briefly
Modern CSS adds @layer, which lets you declare groups of rules with an explicit priority. A layer declared later beats an earlier layer, and this comparison happens before specificity is considered.
@layer base, components;
@layer base {
a {
color: #0b5cad;
}
}
@layer components {
a {
color: #1f2933;
}
}Both rules score (0, 0, 1). The components layer comes later in the @layer list, so links are dark gray. Unlayered author styles beat all layered styles. For a one-page site you rarely need layers, but you will meet them in frameworks and in resets.
Debugging a losing rule
Use the browser's developer tools instead of guessing.
- Right-click the element and choose Inspect.
- In the Styles pane, find the property you expected to change.
- Look for a declaration with a line through it. A struck-through declaration lost the cascade.
- Read the selector of the rule that is not struck through. Compare its score with yours.
- Open the Computed pane to see the final value and which rule supplied it.
A declaration that does not appear at all usually points to a different problem: a typo in the selector, a misspelled property, a missing semicolon in the previous declaration, or a stylesheet that has not loaded. Check the Network tab if the whole file is missing.
Common errors
- Expecting source order to beat specificity. A later rule with a lower score still loses.
- Overusing descendant selectors.
main section div p ascores(0, 0, 5), which is hard to override and breaks when you restructure the HTML. Prefer a short class selector. - Forgetting that inheritance is weakest. A browser default on
areplaces acolorset onbody, which is why links need their own rule. - Assuming
marginorpaddinginherit. They do not. Set them on the element that needs them. - Fighting a rule with
!importantinstead of reading it. Find the winning selector first.
Review
The cascade picks one value per property per element. It compares origin and importance first, then specificity as (IDs, classes, types), then source order. Inheritance supplies a value only when no rule matches the property, and only for properties that inherit by default. Keep selectors short and class-based, order your link states deliberately, and use the Styles pane to see why a rule lost.
Exercise
A page contains <p class="note" id="intro">Hello</p> inside <main>. These rules are in the stylesheet, in this order: p { color: green; }, #intro { color: blue; }, main .note { color: red; }. What color is the text, and why? What would change if you added p { color: orange !important; } at the very top of the file?
Show answer
The text is blue. The scores are (0, 0, 1) for p, (1, 0, 0) for #intro, and (0, 1, 1) for main .note. The ID count is compared first, so #intro wins, regardless of order. If you add p { color: orange !important; }, the text becomes orange, because an important declaration beats every normal declaration, whatever the specificity of the normal ones.
Exercise
You set body { font-family: Georgia, serif; margin: 0; }. A heading inside <main> still has a browser-default top margin, but it uses Georgia. Explain both results, and write one rule that makes buttons use the same font as the page text.
Show answer
font-family is an inherited property, so the heading receives Georgia from body. margin is not inherited, so the heading keeps the margin from the browser's default stylesheet. To make buttons match, use button { font: inherit; }, because browsers give buttons their own font by default and inherit copies the parent's computed value.