CSS - Selectors

Overview

Estimated time: 10–15 minutes

Selectors target elements so you can apply styles precisely. Start with the basics that you’ll use everywhere.

Learning Objectives

  • Use element, class, ID, and universal selectors effectively.
  • Prefer classes over IDs to keep specificity manageable.

Details & Examples

Basic Selectors

  • Element: p { ... }
  • Class: .card { ... }
  • ID: #main { ... }
  • Universal: * { box-sizing: border-box; }

Demo

Element selector (p) sets spacing.

Class selector colors this line.

ID selector makes this bold.

Common Pitfalls

  • Styling with IDs increases specificity; prefer classes.

Checks for Understanding

  1. When would you use the universal selector *?
Show answers
  1. To set global resets like box-sizing for all elements.

Exercises

  1. Refactor a selector using IDs to classes to lower specificity.
  2. Apply a universal box-sizing reset and verify layout stability.
Suggested answers
  1. Change #header .nav to .header .nav with corresponding HTML class updates.
  2. *{box-sizing:border-box} (or include pseudo-elements *,*::before,*::after).