Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 1.4 — Pseudo-classes
CSS · Example 2 of 3

Structural pseudo-classes and nth-child formulas

p:first-child is empty because the first child of .mixed is the h3. Two slots are :empty: the truly empty one and the one with only a comment. The one with a space is not empty.

Pseudo-classes start with one colon and match elements by their state (hovered, focused, checked, disabled, visited) or by their position among siblings (first, last, every second, empty).

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Style a ul.menu so the first item has no top border, every item after it has a 1px grey top border, and the last item is bold, using pseudo-classes.

02

Make every third card in a .grid of .card elements have a gold border, starting with the third.

03

Give a checkbox's label (written right after the checkbox) a line-through when the box is ticked.

Explain it without notes

01

What is the difference between :focus and :focus-visible, and why does it matter for accessibility?

02

Explain li:nth-child(-n+3) and li:nth-child(n+4). What does each match?

03

What is the difference between p:first-child and p:first-of-type? Give a case where only one matches.

04

Why can't you change the font size of visited links?

05

In what order should you write link pseudo-classes, and why?

Structural pseudo-classes and nth-child formulas

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

odd [ '1', '3', '5', '7' ]
3n [ '3', '6' ]
3n+1 [ '1', '4', '7' ]
-n+3 [ '1', '2', '3' ]
n+6 [ '6', '7', '8' ]
p:first-child []
p:first-of-type [ 'P one' ]
p:nth-of-type(2) [ 'P two' ]
p:last-child [ 'P three' ]
empty slots: 2