Css Selector Difference: Element Element vs Element>Element

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

3 Answers

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
div p{} 

This one applies to all p inside div

div>p{}

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

/*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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest