HTML + CSS (Beginner) → Lesson 6

Lesson 6: CSS selectors

Selectors decide what gets styled.

What you'll learn

  • Element, class, and id selectors
  • Basic specificity (simple version)
  • Hover styles

Explain like I'm 10

Selectors are like name tags. You pick what to style.

.card { color: blue; }
#special { color: red; }

Element, class, and id selectors

Element selectors target elements by name (e.g. p), class selectors use a dot (.card) and id selectors use a hash (#special).

p { color: #222; }
/* element */
p { color: #222; }

/* class */
.card { background: #fff; }

/* id */
#special { border-color: red; }

Combining selectors

Combine selectors to be specific about where styles apply, e.g. .card .title selects elements with class title inside an element with class card.

.card .title { font-weight: 700; }

Pseudo-classes: :hover and :focus-visible

Use :hover for mouse hover styles and :focus-visible to show focus outlines for keyboard users.

a:hover { text-decoration: underline; }
button:focus-visible { outline: 3px solid #ffd54f; }

Specificity basics (practical)

Specificity decides which rule wins. Simple rule: IDs beat classes, classes beat elements. Prefer classes for reusable styling; avoid ID overuse.

div { color: black; }
/* element selector (low) */
div { color: black; }

/* class selector (higher) */
.card { color: blue; }

/* id selector (highest) */
#special { color: red; }

The cascade — later rules override earlier ones

If two rules have the same specificity, the one that appears later in the stylesheet wins.

Bad vs Good: id overuse

/* Bad: many ids (hard to reuse) */
#card1 { ... }
#card2 { ... }

/* Good: classes for reuse */
.card { ... }
.card--highlight { ... }

Common mistakes & fixes

  • Forgot the dot: write .class not class.
  • Conflicting selectors: check specificity and order.
  • Styles not applying: ensure the stylesheet is loaded and the selector matches the element.

Practice tasks

  1. Create two cards with the same .card class and style their titles with .card .title.
  2. Make a button show a focus outline using :focus-visible.
  3. Refactor an id-based rule into a class-based rule.

Mini challenge

  • Add a second card with a different class.
  • Make the title size bigger.