Selectors and the Cascade
Site Admin
· 11 Sep 2026
· 8 views
Selectors and the Cascade
CSS selectors determine which elements receive specific styles. The cascade is the algorithm that resolves conflicts when multiple rules target the same element. Understanding both is essential for writing predictable CSS.
Basic Selectors
/* Element selector */
p { color: #333; }
/* Class selector */
.highlight { background-color: yellow; }
/* ID selector */
#header { font-size: 2rem; }
/* Universal selector */
* { box-sizing: border-box; }
Combinators
Combinators create more specific selectors by combining elements:
/* Descendant (any depth) */
article p { line-height: 1.6; }
/* Child (direct only) */
.nav > li { display: inline-block; }
/* Adjacent sibling */
h2 + p { font-size: 1.1rem; }
/* General sibling */
h2 ~ p { margin-left: 1rem; }
Pseudo-Classes and Pseudo-Elements
/* Pseudo-classes */
a:hover { color: #2563eb; }
input:focus { outline: 2px solid #2563eb; }
li:first-child { font-weight: bold; }
li:nth-child(even) { background: #f3f4f6; }
/* Pseudo-elements */
p::first-line { font-weight: bold; }
blockquote::before { content: "\201C"; font-size: 2rem; }
Specificity and the Cascade
When multiple rules conflict, CSS resolves them by specificity: inline styles (highest) > IDs > classes > elements (lowest). Equal specificity is resolved by order - the last rule wins.
/* Specificity: 0-1-0 (one class) */
.card { padding: 1rem; }
/* Specificity: 0-1-1 (one class + one element) */
.card p { margin: 0; }
/* Specificity: 0-2-0 (two classes) - wins over .card p */
.card .text { color: red; }
The !important Rule
!important overrides all specificity. Avoid it - it creates maintenance headaches. Use it only as a last resort.
Key Points
- Class selectors (
.name) are the most commonly used selectors. - Combinators narrow selectors to specific parent-child relationships.
- Pseudo-classes target states like
:hoverand:focus. - Specificity determines which rule wins when multiple rules conflict.
- Avoid
!important- it creates cascading problems.