CSS Combinators

March 7, 2016 by CSS  

Combinators allow us to define relationships between selectors.

Throughout this post we're going to make use the following markup, in order to explain their usage.

<div>
  <p>1</p>
  <p>2</p>
  <span><p>3</p></span>
</div>
<p>4</p>
<span><p>5</p></span>
<p>6</p>

Fiddle.

There are currently three types of combinators available.

  1. Descendant combinator

    The descendant combinator matches elements of the specified descendent selector that are descendants of the specified parent selector.

    div p {
    	color: red;
    }

    Number 1, 2 and 3 gets highlighted in red, the fact that number 3 is a child of a span element is irrelevant, the combinator is interested in all p elements within the parent div regardless.

  2. Child combinator

    The child combinator matches elements of the specified child selector that are immediate children of the specified parent selector.

    div > p {
    	color: red;
    }

    Number 1 and 2 gets highlighted in red, in this case it is important that p elements are direct children of the parent div element.

  3. Sibling combinators

    There are two flavours of sibling combinators.

    1. Adjacent sibling combinator

      The adjacent sibling combinator matches an element of the specified selector that is directly adjacent to the specified sibling selector.

      div + p {
      	color: red;
      }

      Only number 4 will be highlighted, since this selector is only interested in the p element next to the div element.

      What happens when we wrap p>4 with a span element? The selector would fail, since the p element needs to be directly adjacent to the div element.

    2. General sibling combinator (Added in CSS3)

      The general sibling combinator matches elements of the specified selector that are direct siblings of the specified sibling selector.

      div ~ p {
      	color: red;
      }

      Number 4 and 6 will be highlighted, interestingly similar in convention to the child combinator, span>p>5 will be excluded, since its not a direct sibling of the div element.


What about a parent combinator?

Currently there are no parent combinators in CSS and chances are that there will likely never be, I am not going to go into too much detail, Chris Coyier wrote a nice post over here that you can read about the subject.

CSS4 (The Future)

I had a quick glance at the draft for selectors in CSS4 and notice three interesting things in regards to combinators.
 

  1. Adjacent sibling combinator renamed to next sibling combinator.
  2. General sibling combinator renamed to following sibling combinator.
  3. A new combinator added - reference combinator.

    div:matches(:hover) /for/ input {
    	color:red;
    }

    If you hover over the matched div, highlight the matching input field. hmm...


Leave a Comment