Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.1Descendant selector

Part 4.1Descendant selector

In the article in this tutorial on Classes, IDs and tag CSS, selectors were introduced. This article introduced three methods of selection and their CSS code:

CSS
p{
	/*Tag selector*/
}
.class{
	/*Class selector*/
}
#id{
	/*ID selector*/
}
								

These three different options for selecting elements in HTML using CSS are limited however. They give no way of selecting the children of these elements, for instance.

CSS defines a range of more advanced selectors which the next few articles will describe.

Descendant selector

The descendant selector is used to select any descendant (child, grandchild, great-grandchild and so on) of an element.

The descendant selector is very broad and can be used for instance so that different lists display differently. The following sample shows this:

CSS
.special-list li{
	font-weight: bold;
}
								
HTML
<ul class="special-list">
	<li>This is the first element of the list</li>
	<li>This is the second element of the list</li>
	<li>This is a nested list
		<ul>
			<li>This is a nested element</li>
		</ul>
	</li>
</ul>
								
  • This is the first element of the list
  • This is the second element of the list
  • This is a nested list
    • This is a nested element

Using the same HTML, this can be modified to only select elements that are descendants of a ul element that itself is a descendant of an element with .special_list class:

CSS
.special-list li ul li{
	font-weight: bold;
}
								
  • This is the first element of the list
  • This is the second element of the list
  • This is a nested list
    • This is a nested element
Feedback 👍
Comments are sent via email to me.