There are three types of CSS selectors you will encounter most regularly:
- Element selectors, these match all the elements of the same name on the page
p { color: maroon;}- Class selectors, these match all the elements with the specified
classattribute, e.g.<div class="example">
.example { width: 75%;}- ID selectors, this matches the element with the specified
idattribute, e.g.<ul id="gameList'>
#gameList { list-style: cjk-heavenly-stem;}If you can recall the basic structure of a HTML document in the earlier chapter, you can see that HTML elements are nested. And there is no limit to how deep you can nest HTML elements. If you try looking at the source code for a complicated code base, like Facebook, for example, you’ll see a fairly deeply nested HTML structure.
<ul> <li>4 large eggs</li> <li>1/4 cup milk</li> <li>2 tsp. butter</li></ul>
<ol> <li>BEAT eggs, milk, salt and pepper in medium bowl until blended.</li> <li> HEAT butter in large non-stick skillet over medium heat until hot. POUR IN egg mixture. As eggs begin to set, GENTLY PULL the eggs across the pan with a spatula, forming large soft curds. </li> <li> CONTINUE cooking – pulling, lifting and folding eggs – until thickened and no visible liquid egg remains. Do not stir constantly. REMOVE from heat. SERVE immediately. </li></ol>This structure is relevant in the context of CSS as well. Since elements can be children of other elements when they are nested within them, we can target them using descendent selectors. In the above example, we have two different lists. But each list uses li for the list items. If we use just li as the selector, the CSS we write will affect both lists. But if we only want to change the styles on the ingredients list at the top, and not the instructions list at the bottom, we can do this:
ul li { color: maroon;}The selector list is read from right-to-left, with the left-most selector being the parent. If you were to translate the style rule above to plain English, it would read: select all the li elements within ul elements and make their text colour maroon.
Descendent selectors, together with the different categories of selectors we introduced earlier gives us a fairly wide range of combinations to target specific elements, or groups of elements depending on what we want to achieve.
Each combination will yield a different specificity value, which can be predictably calculated, once you understand how it works. Throughout the course, as you delve into different CSS properties, you will be introduced to more selectors in the context where they are used, to make it easier to understand how they work.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson