CSS selector difference: element element vs element>element
Sophia Terry
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.
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>I'm paragraph 1</p> <ul> <li><p>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.
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>