Structural pseudo-classes
Definition and purpose
Structural pseudo-classes select elements based on their position in the element tree. A pseudo-class begins with a colon and adds a matching condition. Use these selectors for repeated lists, table stripes or boundary items without adding positional classes to every element.
Stripe list items
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> li:nth-child(even) { color: navy; } li:last-child { background-color: white; } </style> </head> <body> <ul> <li id="a">One</li> <li id="b">Two</li> <li id="c">Three</li> <li id="d">Four</li> </ul> </body></html>Even positions match; the fourth item also matches last-child.
Syntax and mental model
li:first-child and li:last-child require the first or last element sibling to be li. :only-child requires no other element siblings. :nth-child(2n) selects even positions counting all element siblings from 1; :nth-child(odd) selects odd positions. :nth-last-child() counts from the end. The corresponding -of-type forms count only siblings of the same element type. :root selects the document root; :empty matches elements without element or nonempty text children in the tested browser (whitespace text prevents matching; comments do not). Filtered nth-child lists are taught later.
Child versus type
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> p:nth-child(2) { color: navy; } p:nth-of-type(2) { color: green; } </style> </head> <body> <section> <h2>Heading</h2> <p id="a">First paragraph</p> <p id="b">Second paragraph</p> </section> </body></html>The first paragraph is the second child; the second paragraph is the second of its type.
Common mistakes
Do not confuse the second child with the second element of a given type. Hidden elements still count when they remain in the element tree. CSS numbering here starts at one, not zero.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Attribute selectors. Next lesson: Interaction and link states.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structural pseudo-classes — knowledge check
Five questions on structural pseudo-classes.
Where does nth-child numbering begin?
Which selects even positions?
After a heading, which selects the first p by type?
Does a hidden element still count if present in the element tree?
Which checks there are no other element siblings?