TOC

The community is working on translating this tutorial into French, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Advanced Selectors:

The Child Selector

In the previous chapter, we saw just how powerful the descendant selector can be, because it allows you to target ALL children and grandchildren (and so on) of one or several elements. However, sometimes this can be TOO powerful - sometimes you only want to target the direct children of an element. Fortunately for us, CSS has a selector for this as well!

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!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!