Skip to main content

Structural Pseudo-classes

An element's position in the document tree is what structural pseudo-classes use to select it.


The CSS :first-child Pseudo-class

:first-child matches an element only when it is the first child of another element.

Style all first child <p> elements

Any <p> element that is the first child of its parent is selected.

Prompt
Demonstrate the :first-child pseudo-class by styling all p elements that are the first child of any element with color: blue. Include multiple paragraphs inside different parent elements to show which ones get selected.
Output: complete HTML page

Style the first <em> element in all <p> elements

Inside every <p> element, the first <em> element is selected.

Prompt
Use the selector "p em:first-child" to style the first em element in all p elements with color: blue. Include paragraphs with multiple em elements to show only the first em in each paragraph is selected.
Output: complete HTML page

Style all <em> elements in all first child <p> elements

Here the selection is every <em> element inside a <p> element that is itself the first child of another element.

Prompt
Use the selector "p:first-child em" to style all em elements in p elements that are the first child of another element with color: blue. Include first-child and non-first-child paragraphs with em elements to show the difference.
Output: complete HTML page

The CSS :lang() Pseudo-class

To select elements by the value of their lang attribute, use the :lang() pseudo-class.

Example

Here <q> elements with lang="no" get their own quotation marks.

Prompt
Demonstrate the :lang() pseudo-class. Use q:lang(no) to set custom quotation marks (tildes "~" "~") for q elements with lang="no". Include a paragraph with a q element that has lang="no".
Output: complete HTML page

Other Structural Pseudo-classes

The family of structural pseudo-classes goes further. Among the children of a parent, :last-child picks the last one, :nth-child(n) the nth, :nth-last-child(n) the nth counted from the end, and :only-child an element with no siblings. By type, :first-of-type picks the first element of its type and :last-of-type the last.