Definition
A declarative language used to “select” or target specific elements within an HTML document based on their tag names, IDs, classes, hierarchical relationship, element state, or attribute values.
Why It Matters
The selector model is the “addressing system” of the web. Mastering it allows developers to target elements with surgical precision, creating resilient styles that remain functional even as the underlying document structure evolves.
Core Concepts
- Basic Selector Syntax:
div: All<div>elements.#author: The element withid="author"..notice: All elements withclass="notice".div span: All<span>elements inside a<div>(descendant).div > span: All<span>elements directly inside a<div>(child).input[name]: All<input>elements with anameattribute.
- Grouped Selectors: Comma-separated lists apply the same rule to multiple selectors (
h1, h2, p { color: gray; }). - Pseudo-classes (state/position):
:link,:visited,:hover,:active,:focus,:first-child,:nth-child(n). - Pseudo-elements (sub-parts):
::first-letter,::first-line,::before,::after. - Attribute Selectors:
a[target="_blank"],a[href*="example.com"].
/* Attribute selector */
a[target="_blank"] { color: red; }
/* Direct child selector */
ul > li { list-style: square; }
/* Grouped selector */
h1, h2, h3 { font-family: serif; }