5

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?

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
Walker Farrow
  • 2,859
  • 4
  • 26
  • 50
  • 4
    [Immediate child, any child, and adjacent sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors#Combinators) – Scott Apr 10 '17 at 14:13
  • [CSS '>' selector; what is it?](http://stackoverflow.com/questions/4459821/css-selector-what-is-it) – Simba Apr 10 '17 at 14:16
  • 2
    Have you searched something about those selectors ? ..... – DaniP Apr 10 '17 at 14:17

1 Answers1

24

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>
cнŝdk
  • 28,676
  • 7
  • 47
  • 67