Skip to main content

CSS Combinators

Published on 28th February 2013

It took me a couple of years after learning CSS to actually realise the usefulness and power of CSS combinators. At first they seem quite confusing, but using these combinators will make you a faster and more efficient coder.

So what are CSS combinators?

They are the following characters > (child selector), + (adjacent sibling selector) and ~ (general sibling selector), which are used to combine CSS selectors to target specific pieces of HTML. So let's take a closer look at each one.

Child selector (>)

A child selector selects an element that is a direct child of another element. There is a difference between the basic descendent selector and child selector. Have a look at this example code...

<ul>
  <li>Unordered list item 1</li>
    <ol>
      <li>Ordered list item 1</li>
      <li>Ordered list item 2</li>
      <li>Ordered list item 3</li>
    </ol>
  <li>Unordered list item 2</li>
  <li>Unordered list item 3</li>
</ul>
/* descendent selector */
ul li {
  color: #b2424b;
}
/* child selector */
ul > li {
  color: #b2424b;
}

view demo

The descendent selector CSS will style every list item under the unordered list, even if they are nested inside another unordered or ordered list.

The child selector will only style the list items that are the direct children of the unordered list, and ignore any list items which are nested deeper in the markup.


Adjacent sibling selector (+)

The adjacent sibling combinator will select the first element which is directly after another element. So for example we can select the first paragraph after every heading. Take a look at this code example...

<h1>Heading</h1>
<p>Paragraph 1.</p>
<p>Paragraph 2.</p>
<p>Paragraph 3.</p>
h1 + p {
  font-weight: bold;
  font-style: italic;
}

view demo

Only the first paragraph will be styled with the bold and italicized font, as it's the only paragraph adjacent to the h1.


General sibling selector (~)

The general sibling selector will select every sibling which follows a specified element. Unlike the Adjacent sibling selector, it will select every sibling and not just the first. Take a look at this code example...

<h1>Heading</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
h1 ~ p {
  font-weight: bold;
  font-style: italic;
}

view demo

All paragraphs will be styled with the bold and italicized font, as they all follow the h1.