Basic

Selecting what to style

A selector is a description of the elements you want, and getting the right ones is the whole skill. Element selectors are broad, class selectors are narrow, and the mistake is writing a selector that reaches more than you meant.

What you will see

Only the paragraphs you marked with class="intro". The class is what scopes the style.

About 1 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

See a selector reach more than you meant.

1

Broad rule

p { outline: 2px red; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Every paragraph on the page gets a red outline - that is the set the rule touches.
2

Narrow rule

.intro { outline: 2px red; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Only the paragraphs you marked with class="intro". The class is what scopes the style.

Data Flow

A rule describes elements and applies.
1 Write the selector
↓
2 The browser matches it against the tree
↓
3 The matched elements get the declarations
↓
4 Check the matched set
Why this works
Check what a rule touches

Change one property to something loud, like a red outline, and see which elements change. The visible set is the truth; reasoning about which elements a selector should match is where mistakes hide.

Classes you name after the job

A class called .warning says what the element is for, so the style can change and the meaning stays. A class called .red-text describes the look and forces a rename the moment the design changes.

Examples

Element versus class

p { } styles every paragraph; .lead { } styles the ones you marked. The class is the tool for 'these specific ones', and using it from the start keeps a stylesheet predictable as the page grows.

Descendant selectors

.card h3 { } styles a heading inside a card and nowhere else. That relationship is a normal way to scope a style without adding a class to every element.

The comma is a union

h2, h3 { } styles both. Forgetting the comma gives a descendant selector, which is a different rule that usually matches nothing. That one character is the most common selector bug.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← The elements you actually reach for
Previous Lesson
The elements you actually reach for
Next Lesson
The box model
The box model →