liveBook · Manning

Specificity

As explained in React in Depth

CSS specificity is the priority calculation that determines which applicable CSS rule overrides another when their declarations conflict.

Specificity is the priority calculation that decides which applicable CSS rule wins when declarations conflict. A less-specific rule applies first; a more-specific rule applies afterward. A local purple button override therefore must outrank the normal green button rule, or the button remains green. section 7.1.1

Treat specificity as an architectural concern when CSS grows across components and files:

  • Basic class-based CSS can become unpredictable across files because final rule order is difficult to understand; relying on a fortunate ordering between .button and .custom-button does not scale. section 7.3.5
  • Global class names create collision risk: unrelated .wrapper or .group rules can affect the same elements, especially when a React application is embedded in a regular website. section 7.1.1 section 7.3.5
  • Styled-components removes much of the manual burden by managing rule order and preventing collisions, while keeping styles colocated with the elements they affect. section 7.5.4

A local button override

Start with a general rule such as `.button { color: green; }`. A single purple button needs a competing rule whose specificity is higher than the green rule. In a multi-file application, verify the resulting order rather than assuming `.custom-button` was emitted after `.button`; at scale, that ordering can be difficult to reason about. A styled-components implementation delegates ordering to the library. section 7.1.1 section 7.3.5 section 7.5.4

How React in Depth covers it

How deep it goes
Defines priority, demonstrates a button override, and stops short of detailing the underlying selector-scoring algorithm.
Examples
Uses green and purple button rules, .button and .custom-button, and styled-components rule ordering.
What it assumes
Assumes familiarity with CSS rules, class names, selectors, and declarations while teaching specificity through button overrides.
What you can do after
Diagnose conflicting rules across CSS files and choose managed ordering when component-scale specificity becomes difficult to maintain.
How it connects
Connects specificity with CSS collisions, nesting, pseudoclasses, CSS-in-JavaScript, and styled-components.

Also explained in

Compare how 6 books explain specificity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.