Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 3

CSS Syntax, Selectors & Specificity

The anatomy of a rule, the selector types, and how the cascade decides which style wins.


Anatomy of a CSS Rule

h1 {
  color: blue;
  font-size: 2rem;
}
PartMeaning
SelectorTargets the HTML element(s) to style
PropertyThe style attribute to change (e.g. color)
ValueThe specific style to apply (e.g. blue)
DeclarationA property: value pair, separated by semicolons

CSS Selectors

TypeExampleTargets
Elementh1 { }All <h1> tags
Class.highlight { }Elements with class="highlight"
ID#header { }The unique id="header" element
Attributeinput[type='email'] { }Matches by attribute value (CSS3+)
Pseudo-classa:hover { }Styles based on element state
Parent (2025)div:has(img) { }The long-awaited parent selector — now baseline in all browsers

CSS Specificity & the Cascade

When rules conflict, the more specific rule wins. From highest to lowest priority:

  1. !important — overrides everything
  2. Inline style
  3. ID selector (#id)
  4. Class / pseudo-class
  5. Element selector

2025 tip: use @layer instead of !important to manage specificity without conflicts.

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Match each selector type to its example.

{ color: blue; } /* element */
{ background: yellow; } /* class */
{ font-size: 2rem; } /* id */
a: { color: red; } /* state */