CSS combinators (with code examples)

Written by Keith Devon on October 22, 2020

CSS combinators are powerful tools to target specific elements on a web page.

Here are the four combinators and one fancy use case…


The ‘Descendant’ Combinator

The simplest of the combinators. This matches all of the elements that are descendants of another element.

This example will target all paragraphs that are inside a div and turn them red.

The ‘Child’ Combinator

Using the ‘>’ symbol is like the descendant selector, except that it will only target direct children of an element.

In this example, only h2 elements that are direct children of an article will be bold.

Useful when you don’t want a style to cascade.

The ‘Adjacent Sibling’ Combinator

Now it gets fun. This combinator targets an element that directly follows another element.

The following example targets any paragraph that comes directly after an h1.

The ‘General Sibling’ Combinator

Using the ‘~’ character targets any sibling element that follows another.

This example will target any images that are siblings of, and follow, an h1.

I don’t use this one much!

The ‘Lobotomised Owl’ Combinator

This isn’t a combinator as such, but a use case of the adjacent sibling combinator.

This example will add a top margin to ANY element that follows another element.

No more unnecessary margins! 🤩

Resources

Use the combinators!

I love the power that combinators give you. Especially when combined with other selectors; you can get laser-focused.

Follow Keith on Twitter for more front-end tips and tricks.