Roadmap › HTML5 & CSS3 — Semantic Markup to Responsive Layouts › Module: CSS Fundamentals
Lessons in this course (11)
4. Selectors, the cascade and specificity
Basic★ Must knowLesson 4 of 11
css
p { } /* type */
.card { } /* class */
#main { } /* id */
a:hover { } /* pseudo-class */
p::first-line { } /* pseudo-element */
nav > a { } /* direct child */
h2 + p { } /* adjacent sibling */
input[type="email"] { } /* attribute */
.card:has(img) { } /* parent selector (modern) */Which rule wins? The cascade, in order:
- Origin and importance (
!importantbeats normal; user-agent < author). - Cascade layers (
@layer) order. - Specificity — (ids, classes/attributes/pseudo-classes, elements):
| Selector | Specificity |
|---|---|
p | 0,0,1 |
.card p | 0,1,1 |
#main .card p | 1,1,1 |
inline style="" | beats all selectors |
- Source order — later wins when specificity is equal.
Inheritance: text properties (color, font-*, line-height) inherit; box properties (margin, border, width) don't.
Interview tip: Avoid
!importantand id selectors for styling — keep specificity low and flat (classes), so styles are easy to override.