CSS – child vs descendant selector examples

CSS direct child can be specified using A > B and any descendant can be specified using A B. This should be used with care as it can lead to surprises in case there are nested elements in html.
css-direct-child-vs-descendant

Direct child (A > B) example

Here background color of any direct child is changed to lightgray.

<style type="text/css">
.foo > p {background:lightgray;}
</style>
<div class="foo">
<p>direct child1</p>
<p>direct child2</p>
<div><p>descendant</p><div>
</div>
refresh

Any descendant (A B) example

Here background color of any descendant is changed to lightgray. This will change color of all descendants including all direct children also.

<style type="text/css">
.foo p {background:lightgray;}
</style>
<div class="foo">
<p>direct child1</p>
<p>direct child2</p>
<div><p>descendant</p><div>
</div>
refresh

Related

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments