CSS Essentials
This page demonstrates selectors, specificity, and the box model — the foundation of all CSS.
1. Selectors
Selectors target the HTML elements you want to style.
Common Selector Types
- Element selector – targets all instances of a tag (
p) - Class selector – targets elements with a class (
.highlight) - ID selector – targets one unique element (
#special-text) - Attribute selector – targets elements with a specific attribute
- Pseudo-class – targets a state (
:hover,:focus) - Pseudo-element – targets a part of an element (
::before,::after)
This paragraph has a highlighted span using a class selector.
This paragraph is targeted by an ID selector.
2. Specificity
When multiple rules target the same element, the one with the highest specificity wins.
This text has three competing rules. The ID selector wins (it appears red).
Specificity Rank (simplified)
- Inline styles (highest)
- ID selectors (
#id) - Class, attribute, and pseudo-class selectors (
.class,:hover) - Element and pseudo-element selectors (
p,::before)
Teaching tip: Prefer classes over IDs for styling. Save IDs for JavaScript hooks and unique page landmarks.
3. The Box Model
Every element is a box made of four parts (from inside out): content → padding → border → margin.
Total width = 200 + 40 + 16 = 256px
Much easier to reason about.
Best practice: Set box-sizing: border-box; globally
(we already did this in the reset at the top of styles.css).