Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Selectors - difference between and when to use ">", "+" or " " [duplicate]

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?

like image 378
Walker Farrow Avatar asked Apr 10 '17 14:04

Walker Farrow


1 Answers

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>
like image 75
cнŝdk Avatar answered Sep 23 '22 00:09

cнŝdk