Multi-class Selectors Question

From “Test your skills: Selectors” (https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks), the “Selectors Two” test.

I have not been able to figure-out why the rule for “.alert .stop” (with a space between them) works, but “.alert .go” does not. They both work as “.alert.stop” / “.alert.go”.

I went into the Web Inspector, and the class info for both of them looks the same:

classList: DOMTokenList
0: “alert”
1: “stop” (or “go”)
length: 2
value: “alert stop” (or “go”)

Any idea why they would behave differently?

HTML/CSS here: codepen.io/rrohweder/pen/PoGyEYx

Hi @Roger_Rohweder, and welcome to the community!

So, looking at your sample code, neither .alert .stopnor .alert .go are doing anything. These will only select:

  • an element with a class of stop, which is inside an element with a class of alert
  • an element with a class of go, which is inside an element with a class of alert

respectively.

the elements with class="alert stop" or class="alert go" on them won’t be selected by either of the above two selectors, but they will still be styled by the following rule:

.alert {
     border: 3px solid grey;
}

.alert will select any element with a class of alert on it, regardless of whether it has other classes set on it or not.

Now, moving on to .alert.stop and .alert.go. Respectively, these will select:

  • An element with alert and stop classes set on it.
  • An element with alert and go classes set on it.

So for example, <span class="alert stop"> is being styled by both of the following rules:

.alert {
     border: 3px solid grey;
}
.alert.stop {
     border: 3px solid red;
}

Hope this helps — one tip that helped me to figure out what is going on (as I’m a bit color blind!) is to give the rules with the .alert.stop and .alert.go selectors a bigger border (e.g. 6px solid black) so it is easier to see when they are or aren’t being applied.

Thank for the quick reply. What threw me yesterday was that the “.alert .stop” (with a space) border was turning red in the embedded test iframe. This morning it does not. I understand your explanation, and will assume that my brain or the environment hiccuped, and move on.

You are welcome, glad to help.