CSS combinators (with code examples)

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! 🤩

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.

About the author

Co-founder and lead front-end developer at Highrise Digital. Keith has a passion for building beautiful, fast and usable websites.