Advanced

Pseudo classes and states

A pseudo class describes a state or a position rather than a thing you marked: hover, focus, first child, every other row. They are the way to style states without adding markup, and the way to write selectors that are hard to read.

What you will see

Tabbing to the link now shows it. That rule is the accessibility fix and it is the one most audits look for.

About 1 min of reading

Try It

Give a link all its states.

1

Hover only

a { color: #06c; } a:hover { color: #039; }

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

What it prints
The link changes on mouse over and shows nothing when reached by keyboard.
2

Add focus

a:focus { color: #039; outline: 2px; }

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

What it prints
Tabbing to the link now shows it. That rule is the accessibility fix and it is the one most audits look for.

Data Flow

A state selects without markup.
1 The element enters a state
↓
2 The pseudo selector matches it
↓
3 The state rule applies
↓
4 The look changes without new HTML
Why this works
Focus is not optional

A page where only hover changes the look has no visible keyboard state. Styling focus is a two line rule that fixes a real accessibility failure, and it is the one that is checked most often.

Do not hide meaning in CSS

Content generated by CSS is not in the HTML, so a reader, a search, and a copy of the page do not see it. Put real words in HTML and use generated content for marks and decoration.

Examples

States of an element

hover, active, and focus style the same element in different situations. A link needs all three, and a control that only has hover is a control that cannot be seen as selected with a keyboard.

Position in a parent

first-child, last-child, and nth-child select by position. That is how a table row can stripe without a class per row, and how a list can drop the margin on its last item.

Generated content

before and after insert content you did not write in HTML. Useful for decoration, and a trap for meaning: text generated in CSS is not part of the document in the way a reader expects.

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.

← Custom properties and theming
Previous Lesson
Custom properties and theming
Next Lesson
Positioning and stacking
Positioning and stacking →