CSS Selectors - difference between and when to use

2019-02-16 06:46发布

问题:

This question already has an answer here:

  • CSS '>' selector; what is it? [duplicate] 7 answers
  • What does the “+” (plus sign) CSS selector mean? 11 answers

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?

回答1:

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>