Advanced CSS selectors

Selection of a direct child element

#parent > .child

Select the elements with the class child that are direct children of the element with the identifier parent.

Use case: several nested elements - e. g. menus - but only the first level is selected.

Selection of an adjacent element (or sibling element)

.abel + .cain

We select the elements with the class cain that follow elements with the class abel.

Use case: try to select an element that is systematically after another, but difficult to point effectively by itself.

Selection of the n-th element (of an implicit direct parent)

To select an element by its position within its parent, you can use :nth-child() (means “n-th child element”) with, as a parameter, the position of the element to select.

Example:

a:nth-child(2)

Selects all the links that are the second child of their direct parent.

Selection of an element with exclusion

To select an item provided it does not match another simple selector, you can use :not() with the selector to exclude as a parameter.

Example:

a:not(.excluded)

Selects all links that do not have the exclude class.

Other selectors

There are many CSS selectors and new ones are regularly added: we recommend “Learn more” section of MDN documentation.

TIP
CSS still does not allow you to select an element according to its textual content, nor to select a parent element according to its children. For these purposes, you can use XPATH selectors.

Back to Table of Contents