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.

7
  • 2
    The > combinator separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
    – emmanuel
    Commented Nov 16, 2014 at 13:03
  • Here's an example: 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
    Commented Nov 16, 2014 at 13:06
  • possible duplicate of What does the ">" (greater-than sign) CSS selector mean?
    – emmanuel
    Commented Nov 16, 2014 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 !
    – user3522371
    Commented Nov 16, 2014 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
    Commented Nov 16, 2014 at 13:14

3 Answers 3

42

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.

3
  • 1
    Could the downvoter explain what they don't like about this answer? Commented Nov 16, 2014 at 13:10
  • 1
    I found it perfectly helpful. I didn't understand how a direct descendant was different and this explained it thanks.
    – Smithy
    Commented Nov 16, 2014 at 13:12
  • This is super cool and simple explanation.... thank @Jason Baker
    – gkd
    Commented Jun 23, 2020 at 16:51
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

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>

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