liveBook · Manning

CSS selector

As explained in CSS in Depth, Second Edition

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

A CSS selector is the part of a ruleset that identifies the element or elements receiving the declarations inside its declaration block. Together, the selector and block form a ruleset. section 1.0

Selecting a page heading

Given a heading with the ID page-title and the classes title, three rulesets can target the same element: h1, #page-title, and .title. When their font declarations conflict, the ID selector has greater specificity and produces the sans-serif result. section 1.1

Selectors participate in the cascade, where stylesheet origin, inline styles, layers, specificity, scope proximity, and source order resolve competing declarations. Specificity counts IDs, classes, and tag names, making the browser’s choice predictable. section 1.1 section 1.6

Selectors also affect progressive enhancement. A browser that does not understand a selector ignores its entire ruleset; if one selector in a comma-separated list is unsupported, separate the selectors into independent rulesets to preserve the fallback. section 1.5.2

body {
  color: black;
  font-family: Helvetica;
}

Use this compact ruleset to distinguish the selector from its declaration block and see both parts together. section 1.0

input.invalid {
  border: 1px solid red;
}
input:user-invalid {
  border: 1px solid red;
}

Compare separate rulesets for a class selector and a newer pseudo-class so unsupported browsers retain the class-based styling. section 1.5.2

How CSS in Depth, Second Edition covers it

How deep it goes
Defines selectors, demonstrates specificity through conflicting rulesets, and explains unsupported-selector fallbacks without surveying every selector type.
Examples
Uses body, h1, ID, class, invalid-input, and user-invalid selectors in page-header, navigation, heading, and form examples.
What you can do after
Evaluate which competing CSS rule wins and apply selector fallbacks that preserve styling when newer syntax is unsupported.
How it connects
Connects selectors to declaration blocks, rulesets, the cascade, specificity, inheritance, pseudo-classes, pseudo-elements, and attribute selectors.

Also explained in

Compare how 8 books explain CSS selector →

Related concepts

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