Question about chaining CSS selectors and specificity


#1

Hello! I am currently completing the CSS Setup and Selectors lesson and I am on Exercise 14 about chaining and specificity. I understand the basics of what is going on here, but I am a bit confused about one of the tasks.

https://www.codecademy.com/courses/learn-css-selectors-visual-rules/lessons/css-setup-selectors/exercises/nested-elements?action=lesson_resume&course_redirect=learn-css

Earlier, in a previous exercise, they showed us you could chain selectors by adding a class selector to a tag

For Example:

```
h1.special {

}

But then in the next exercise it asked me to add a selector that targeted the “h5” element with the class “description”. So I wrote mine like this:

h5.description {

}

Which worked in the browser but it was marked red in the exercise. When I checked the code, it was supposed to be written like this:

.description h5 {

}

So my main question is this…What is the difference between the order here? Is there a specific reason it had to be written like this? Or could it be either way? Thanks in advance for the help!


#2

these selectors work different, h5.description selects all h5 elements which have class description:

h5.description {
    color: red;
}

<h5 class='description'>i am red</h5>
<h5>i am not red</h5>

where as .description h5 selects all h5 elements which are a child of element with class description:

.description h5 {
    color: red;
}

<div class='description'>
    <h5>i am red</h5>
</div>
<h5>i am not red</h5>

the h5 element doesn’t have to be a direct child of element with class description


#3

Ah gotcha…thanks! :grin:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.