This article is currently in the process of being translated into Spanish (~20% done).
The Child Selector
En el capítulo anterior, vimos lo poderoso que puede ser el selector descendiente, porque le permite apuntar a TODOS los hijos y nietos (y así todos) de uno o varios elementos. Sin embargo, a veces esto puede ser demasiado potente - a veces sólo desea apuntar a los elementos secundarios directos de un elemento. Afortunadamente para nosotros, CSS tiene un selector para esto también!
In the previous chapter, we had an example with a descendant selector which automatically targeted all bold tags all the way down through the hierarchy:
<style type="text/css">
div.highlighted b {
color: Blue;
}
</style>
<div class="highlighted">
<b>Level 0...</b>
<div>
<b>Level 1...</b>
<div>
<b>Level 2...</b>
</div>
</div>
</div>
The syntax for using the direct child selector looks like this:
parent > child
So, re-writing the above example to only affect direct children of the div.highlighted tag is very easy:
<style type="text/css">
div.highlighted > b {
color: Blue;
}
</style>
<div class="highlighted">
<b>Level 0...</b>
<div>
<b>Level 1...</b>
<div>
<b>Level 2...</b>
</div>
</div>
<b>Level 0 again...</b>
</div>
Notice how we now have what we wanted - only direct children of the parent are now affected.
Of course, you can add more requirements to the selector, both of the descendant and the child type. Take for instance this example:
<style type="text/css">
div.highlighted > ul > li > a {
color: DarkOrange;
}
</style>
<div class="highlighted">
<ul>
<li><a href="#">List Link 1</a></li>
<li><a href="#">List Link 2</a></li>
<ul>
<li><a href="#">List Link 2.1</a></li>
</ul>
<li><a href="#">List Link 3</a></li>
</ul>
</div>
Notice how I've just made the selector rule more specific than what we have previously seen - instead of just targeting e.g. links inside the ".highlighted div" or links inside a list, I target links which is a direct child of a list item tag, which is a direct child of an unordered list which is a child of a div tag with the "highlighted" class. So even though we have a child list inside of the list, its links won't be affected by this rule and if you add another list which is not inside of the highlighted div, it won't be affected either.
Summary
The child selector is a more specific version of the descendant selector, but that doesn't make it less powerful. You are very likely to run into situations where either of them can help you simplify your CSS code!