Combinators in CSS are used to combine multiple CSS selectors. Combinators can be used in creative ways to select large groups of elements or increase specificity. The four types of combinators are,

  1. Descendant combinator (space)
  2. Child combinator (>)
  3. General sibling combinator (~)
  4. Adjacent sibling combinator (+)

Watch video instead:

Descendant combinator

Descendant combinator is simply the space character. As the name implies, it selects the descendants.

div p {
    color: red;

The above CSS selects all paragraph that are descendants of div element. You can combine multiple descendant combinators to increase specifcity. CSS rules are overrided depending on specifcity.

Child combinator

Child combinator selects the direct children of the parent combinator.

div > p {
    color: red;

The difference between above two codes is that the the first one will select all paragraph elements that comes under a div. The second one will only select the direct children. So if there are paragraphs nested inside some other tags, styles won't be applied to them.

General sibling combinator

General sibling combinator selects all elements that comes after a specified element.

div ~ p {
    color: red;

The above CSS will select all paragraphs that comes after a div. It doesn't matter even if there is other html tags in between. All paragraphs the comes after a div will be selected.

Adjacent sibling combinator

Adjacent sibling combinator selects the element that comes after a specified element.

div + p {
    color: red;

The above CSS selects all paragraphs that comes just after a div. This is useful for spacing purposes. For example, if you want to add space on top of images that comes just after a section.

Written by Aravind Sanjeev, an India-based blogger and web developer. Read all his posts. You can also find him on twitter.