CSS Selectors
~310 words ยท 2 min read
How CSS selectors target elements
A selector is the pattern that tells CSS which elements to style. Selectors range from simple to highly specific, and mastering them is the key to writing CSS you can actually control.
The three basic selectors
- Element โ
pmatches every paragraph. - Class โ
.btnmatches any element withclass="btn". Reusable across many elements. - ID โ
#logomatches the single element with that id. Unique per page.
Combinators
Combine selectors to target nested elements precisely:
/* descendant โ any .item anywhere inside .list */
.list .item { }
/* child โ only DIRECT children */
.list > .item { }
/* adjacent sibling */
h2 + p { margin-top: 0; }
The descendant combinator (a space) matches at any depth. The child combinator (>) matches only immediate children โ stricter and often safer.
Pseudo-classes
A pseudo-class targets an element's state, selected with a colon:
a:hover { color: red; }
input:focus { border-color: blue; }
li:nth-child(odd) { background: #eee; }
Note: pseudo-classes (:hover) describe state, while pseudo-elements (::before) create or style a part of an element โ the double colon distinguishes them.
Specificity
When two rules collide, the more specific one wins. Specificity is a three-part score (ID, class, element):
#nav .itemโ (1, 1, 0)div .itemโ (0, 1, 1)
IDs beat classes, classes beat elements. Only !important overrides specificity โ use it sparingly, because it becomes a maintenance trap.
Prefer classes over IDs for styling. IDs are extremely specific and hard to override, which fights you as a codebase grows.