CSS Combinators

In CSS a Combinator describes the relationship between two basic selectors and comes in four different forms, which are described below.

Descendant Selectors

Descendant Selectors allow you to target elements based on their relationship with other elements and can involve any combination of the basic selectors. The below example only targets paragraphs that are inside a 'div' element and makes the text colour blue.

HTML:

<div>
   <p>This is a paragraph with blue text.</p>
</div>

CSS:

div p {
   color: blue;
}

This example targets all paragraphs with the class 'blue' inside an element that has an ID of 'main'.

HTML:

<div id="main">
   <p class="blue">This is a paragraph with blue text.</p>
</div>

CSS:

#main p.blue {
   color: blue;
}

Note that in both the above examples the paragraphs could have been nested inside another element within the 'div' and would still be styled as described.

Child Selector

Child Selectors go further than Descendant Selectors and only target a child element directly inside another element. This is done by using the '>' combinantor. The example below just targets a paragraph directly inside the 'div' element.

HTML:

<div>
   <p>This is a paragraph with blue text.</p>
</div>

CSS:

div > p {
   color: blue;
}

With the above CSS, the paragraph in the HTML below would not have blue text because it is within a 'span' element inside the 'div' element.

<div>
   <span>
      <p>This paragraph does not have blue text.</p>
   </span>
</div>

Adjacent Sibling Selector

An Adjacent Sibling Selector targets the adjacent element, or element that immediately follows another element, using the '+' combinator. In the example below the paragraph that immediately follows the 'div' element is given blue text.

HTML:

<div>
   <p>This paragraph does not have blue text.</p>
</div>
<p>This is a paragraph with blue text.</p>
<p>This paragraph does not have blue text.</p>

CSS:

div + p {
   color: blue;
}

General Sibling Selector

A General Sibling Selector targets all elements of a particular type, that are siblings of another element, using the '~' combinator. The following example targets all paragraphs that follow a 'div' element and again makes the text blue.

HTML:

<div>
   <p>This paragraph does not have blue text.</p>
</div>
<p>This is a paragraph with blue text.</p>
<p>This is a paragraph with blue text.</p>
<p>This is a paragraph with blue text.</p>

CSS:

div ~ p {
   color: blue;
}