liveBook · Manning

CSS selector

As explained in Acing the Frontend Interview

A CSS selector is a pattern that identifies the document elements to which a set of CSS declarations applies.

A CSS selector identifies which elements receive a rule’s declarations. In an interview, be ready to explain not just what a selector matches, but what happens when several matching rules set the same property. 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>
);

Trace the button example by property: `.container .primary-button` supplies the green background, while `#my-button` supplies the yellow text. This is more precise than saying that one rule wins overall. section 2.2

For maintainable CSS, prefer simple class selectors over deep nesting and IDs when possible. This also appears among the suggested CSS performance optimizations. section 2.2

How Acing the Frontend Interview covers it

How deep it goes
Works through selector specificity in a React button example and gives selection guidance, without detailing selector-matching internals.
Examples
Compares element, class, nested-class, and ID selectors applied to a React button.
What you can do after
Diagnose/debug with it by tracing which matching selector supplies each button property.
How it connects
Connects selectors to CSS specificity, CSS declarations, React components, and CSS performance.

Also explained in

Compare how 9 books explain CSS selector →

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.