6

When using CSS, I can query elements in the following ways:

div > .class  
div .class 
div + .class 

However I can't quite tell the exact difference between each of these DOM queries. Do they all point to child elements? I know that ">" and " " (space) do.

But under what circumstances would I use each?

3

1 Answer 1

29

In CSS these are called Combinators and means three different things:

  1. div > .class: is called Child selector and will select all elements that are direct children of a div and have the class .class.

  2. div .class: is called Descendant selectors and will select all elements inside a div and having the class .class.

  3. div + .class: is called Adjacent sibling selector and will match any element that immediately follows a div and have the class .class.

Example:

In the following example:

<div>
  <p class="test">
    <a href="#" class="test">
      Testing link</a>
    <img class="test"/>
  </p>
  <span class="test">A span</span>
</div>
<h4 class="test">A title</h4>
  • div > .test will match only <p> and <span> elements.
  • div .test will match <p>, <a>, <img> and <span> elements.
  • div + .test will match only <h4> element because it follows the <div> immediately.

Demo:

div .test {
  background: yellow;
}

div>.test {
  background: red;
}

div+.test {
  background: green;
}
<div>
  <p class="test">
    Pragraph
    <a href="#" class="test">
      link</a>
    <img class="test" width="50px" height="50px" />
  </p>
  <span class="test">Span</span>
</div>
<h4 class="test">Title</h4>

1
  • 1
    It's better to let the code explain what the answer is, and you did the same. 👌
    – Ayub
    Commented Dec 4, 2020 at 16:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.