CSS chapters

Chapter 8 of 17

Repeated styling with selectors

Try this in our CSS Compiler →

The idea

CSS does not implement for, while, break or continue. A rule automatically applies to every matching element. Structural pseudo-classes such as :nth-child() select positions; they do not iterate a mutable counter. Use classes when the distinction is about meaning instead of position.

Worked example

li { padding: 8px; }
li:nth-child(odd) { background: lightcyan; }

What to check

Odd-position list items receive the background. Adding an item changes later positions, which may change which elements match.

Practice task

Compare :nth-child(2) with :nth-of-type(2) in a parent containing different element types. Inspect which element each matches.

Check your understanding

Explain the result in your own words before changing the example. Change one thing at a time, compare the result with your prediction, and keep the version that demonstrates the concept clearly.

Try it yourself

Output
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on