Software Development | CSS Combinators

CSS Combinators

Overview

Sometimes it is useful in CSS to select very specific elements or groups of elements without defining and applying another class. Combinators join selectors to target descendants, children, adjacent siblings, and general siblings (all of the following siblings).

"They are called combinators, because they combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document." – MDN

The four CSS combinators
Combinator Symbol Example Selects
Descendant (space) article p Every p anywhere inside an article
Child > ul > li Every li that is a direct child of a ul
Next sibling (adjacent) + h2 + p A p that immediately follows an h2
Subsequent sibling (general) ~ h2 ~ p Every p that comes after an h2 and shares its parent

Prepare

Activity Instructions

  1. Read CSS Combinators on w3schools.com and complete the combinator exercises at the end of the page.
  2. Use an AI tool to help you write a selector for the second paragraph in a given article.
    One prompt you could try: CSS select the second p of an article with the class of "info"
Screenshot of finished combinator exercises from w3schools.com
Screenshot of completed w3schools.com combinator exercises