liveBook · Manning

Specificity

As explained in Acing the Frontend Interview

CSS specificity is the precedence system browsers use to determine which matching style declaration wins when rules conflict.

CSS specificity helps determine which declaration wins when multiple matching selectors set the same property. In an interview, explain the result for each property rather than naming one winning rule for the entire element. section 2.2

Which styles reach the button?

A button inside `.container` matches `button`, `.primary-button`, `.container .primary-button`, and `#my-button`. Its background is green: the two-class selector overrides the single-class and element selectors for that property. Its text is yellow: the ID selector overrides the class and element color declarations. The `.button` rule still supplies padding, font size, and a pointer cursor. section 2.2

Listing 2.6 CSS specificity example
const styles = `
  .button {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
  }
  .primary-button {
    background-color: blue;
    color: white;
  }
  button {
    background-color: red;
    color: black;
  }
  .container .primary-button {
    background-color: green;
  }
  #my-button {
    color: yellow;
  }
`;
interface ButtonProps {
  children: React.ReactNode;
  id: string;
}
const Button: React.FC<ButtonProps> = ({ children, id }) => (
  <button className="button primary-button" id={id}>
    {children}
  </button>
);
const CssSpecificityExample = () => (
  <div className="container">
    <style>{styles}</style>
    <Button id="my-button">Click me</Button>
  </div>
);

Inspect the complete React and TypeScript example, then identify every selector matching the rendered button before deciding its background and text colors. section 2.2

For maintainable CSS, prefer simple class selectors where possible and avoid deep nesting or unnecessary IDs. Be ready to explain both how you resolved a style conflict and whether the selectors could be simpler. section 2.2 section 2.5

How Acing the Frontend Interview covers it

How deep it goes
Works through competing selectors and their resulting styles, without presenting a numeric specificity formula.
Examples
Uses a React button matched by element, class, nested-class, and ID selectors.
What it assumes
Uses CSS selectors and React component markup without introducing their fundamentals.
What you can do after
Diagnose/debug with it: identify which matching declaration supplies each button style and explain the result.
How it connects
Connects specificity to CSS selectors, style conflicts, and selector simplification.

Also explained in

Compare how 7 books explain specificity →

Related concepts

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