Selectors & Specificity

🎨 CSS Basics Lesson 2 Beginner

Selectors are patterns that tell the browser which HTML elements to style. Mastering selectors is the single most important CSS skill — everything else builds on it.

1 Core Selector Types
CSS — Selector Types
/* Element selector — targets all matching tags */
p { color: #374151; }

/* Class selector — targets class="card" */
.card { border-radius: 8px; padding: 16px; }

/* ID selector — targets id="hero" (unique per page) */
#hero { background: #1e1b4b; color: white; }

/* Attribute selector */
a[target="_blank"] { color: orange; }

/* Descendant selector — p inside .card only */
.card p { font-size: 0.9rem; }

/* Child combinator — direct children only */
.nav > a { font-weight: 600; }

/* Multiple selectors */
h1, h2, h3 { font-family: 'Inter', sans-serif; }
2 Specificity Scoring

The browser calculates a specificity score for every rule. Higher score wins.

SelectorScore
Inline style1-0-0-0
ID #id0-1-0-0
Class / Attribute / Pseudo-class0-0-1-0
Element / Pseudo-element0-0-0-1
Universal *0-0-0-0
CSS — Specificity Example
p            { color: black; }   /* score: 0-0-0-1 */
.intro p     { color: gray;  }   /* score: 0-0-1-1  ← wins */
#main .intro p { color: blue; }  /* score: 0-1-1-1  ← wins */
3 Code Challenge
Challenge: Write a stylesheet where an element selector, a class selector, and an ID selector all try to set the same property. Verify which rule wins and explain why using specificity scores.