13

What is the difference between the following two CSS selectors?

From the explanation here, they sound the same?

div p{}

Selects all p elements inside div elements

div > p{}

Selects all p elements where the parent is a div element.

Smithy
  • 385
  • 1
  • 5
  • 15
  • 2
    [The > combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors) separates two selectors and **matches only those elements** matched by the second selector that are **direct children** of elements matched by the first. – emmanuel Nov 16 '14 at 13:03
  • Here's an example: http://jsfiddle.net/wj8wm9fe/ That said, this isn't a good question. You could easily have figured out the difference with a bit more research. – Index Nov 16 '14 at 13:06
  • possible duplicate of [What does the ">" (greater-than sign) CSS selector mean?](http://stackoverflow.com/questions/3225891/what-does-the-greater-than-sign-css-selector-mean) – emmanuel Nov 16 '14 at 13:06
  • 4
    why this severe down vote ?? Incredible ! He did not kill any one, he just asks explanation for something he does not understand ! –  Nov 16 '14 at 13:13
  • The duplicate suggestion answers this question. I should have searched better. No idea what I should do in this situation - delete this question? Sorry! – Smithy Nov 16 '14 at 13:14
  • you can unaccept the answer and do not vote on any of the answers. Then you can delete your question –  Nov 16 '14 at 13:21
  • I'd say the "duplicate" question does not answer this question fully. This question asks for the difference between `element element` and `element>element`. The other does not explain the difference, but only how the `element>element` selector operates. – GGG Dec 12 '16 at 03:20

3 Answers3

41

The difference is depth. What the w3schools site doesn't explain very well is that E>F only matches immediate children of E, while E F matches descendants of any depth.

Using your example CSS, consider the following HTML snippet:

<div>
    <p id="paragraph1">I'm paragraph 1</p>
    <ul>
        <li><p id="paragraph2">I'm paragraph 2</p></li>
    </ul>
</div>

The first ruleset, div p, will match both p blocks. The second one, div > p, will only match paragraph1.

Jason Baker
  • 2,471
  • 3
  • 23
  • 28
4
div p{} 

This one applies to all p inside div

div>p{}

This one says p needs to be a direct descendent of div

optimus
  • 834
  • 1
  • 10
  • 22
3

/*This one applies to all childrens (`span`) inside parent*/
div span {
    color: red;
}

/*This one says child (`span`) needs to be a direct descendent of parent*/
div > span {
    color: green;
}
<div>
  <!--(`div`) does not represent an obstacle in both selectors-->
  <div>
    <span>I live in Duckburg.</span>
  </div>
  <ul>
    <li>
      <span>I live in Duckburg.</span>
    </li>
  </ul>
  <span>I live in Duckburg.</span><br>
  <span>I live in Duckburg.</span>
</div>
alessandrio
  • 4,282
  • 2
  • 29
  • 40