Skip to main content

CSS Combinators

Combinators express how two or more selectors relate to each other.

One CSS selector may be built from several selectors, and placing a combinator between them makes the selection more specific.

CSS offers four of them: descendant combinator (space), child combinator (>), next sibling combinator (+), and subsequent-sibling combinator (~).


Descendant Combinator (space)

Children, grandchildren and anything deeper all count as descendants, and this combinator matches every one of them under the specified element.

Example

Every <p> inside a <div> gets selected.

Prompt
Demonstrate the descendant combinator (space). Use the selector "div p" to set background-color: yellow on all paragraphs inside a div. Include paragraphs both inside and outside the div to show the difference.
Output: complete HTML page

Child Combinator (>)

Only direct children of the specified element are selected by the child combinator.

Example

A <p> is selected here only if it is a direct child of a <div>.

Prompt
Demonstrate the child combinator (>). Use the selector "div > p" to set background-color: yellow on paragraphs that are direct children of a div. Include nested paragraphs inside inner elements to show only direct children are selected.
Output: complete HTML page

Next Sibling Combinator (+)

Two elements are siblings when they share a parent. The next sibling combinator selects the one element placed directly after the specified element.

Example

Only the first <p> coming immediately after a <div> gets selected.

Prompt
Demonstrate the next sibling combinator (+). Use the selector "div + p" to set background-color: yellow on the first paragraph that immediately follows a div element. Include multiple paragraphs after the div to show only the first one is selected.
Output: complete HTML page

Subsequent-sibling Combinator (~)

Where the previous combinator stops at one element, the subsequent-sibling combinator selects every next sibling of the specified element.

Example

Every <p> that comes after a <div> as its sibling gets selected.

Prompt
Demonstrate the subsequent-sibling combinator (~). Use the selector "div ~ p" to set background-color: yellow on all paragraphs that are siblings after a div element. Include paragraphs both before and after the div to show the difference.
Output: complete HTML page