Codecademy Forums

CSS Selectors hierarchy

I’m in the CSS basic course, step 12 “Chaining Selectors” and it states:

Chaining Selectors

When writing CSS rules, it’s possible to require an HTML element to have two or more CSS selectors at the same time.

This is done by combining multiple selectors, which we will refer to as chaining. For instance, if there was a .special class for h1 elements, the CSS would look like:

In the previous step it mentioned that IDs are the most specific and will override all other selectors. Is it possible to chain id and class selectors together, or even all 3 to keep CSS formating to a very specific area when id, class, and tag selectors all share a common line of code?

1 Like

Well, chaining IDs with classes is not necessary since there is only one HTML element with that particular ID tag. You can however chain classes to target specific elements. Even more so there are even CSS selectors that can for example select the next sibling of an element or the first parent.

For a complete list of selectors go here ;).

The only reason I can think of to chain a class to an ID is in the case that you have multiple elements of a certain tag under a div with an ID.

Say you have two sections with separate IDs yet the child elements are of the same class but you want to implement only one difference ( i.e. font colour).

The HTML:

<div id='parent1'>
     <div class="child"></div>
     <div class="child"></div>
     <div class="child"></div>
     <div class="child"></div>
</div>

<div id='parent2'>
     <div class="child"></div>
     <div class="child"></div>
     <div class="child"></div>
     <div class="child"></div>
</div>

The CSS:

.child {   /* Targets all elements with a class of .child */ 
   font-size: 20px;
   text-align: center;
   font-weight: bold;
   color: blue;
}

#parent2 .child { /* Only targets the elements with a class of .child which are children of the div element with an ID of #parent2 */
   color: red;
}

Does this answer your question?

4 Likes