0

There is a situation that I need to change the class priority. For example:

.one {
  color: green;
}

.comment {
  color: gray;
}

.red {
  color: red !important;
}
<div class="one two red">Content</div>
<div class="comment two red">Content</div>

At the moment, .red color is applied. Is it possible to force .comment.red to get the color from .comment?

Note: The .comment color is unknown (comes from changeable themes).

j08691
  • 204,283
  • 31
  • 260
  • 272
erosman
  • 7,094
  • 7
  • 27
  • 46

1 Answers1

3

Yes, you can use multiple classes to make it more specific. Also, we know that .comment.red needs to have min two classes. So I feel this is allowed:

.one {
  color: green;
}

.comment.comment {
  color: gray;
}

.red {
  color: red;
}
<div class="one two red">Content</div>
<div class="comment two red">Content</div>

But please get rid of !important.

The .comment's rule, instead of it being like this:

img

We can make it like this:

img

More Explanation

Modern browsers compute the style contexts using the rule tree. If multiple rules have the same weight, origin and specificity, the one written lower down in the stylesheet is considered and wins.

When there's only one selector here:

.class1 {}

The weight of the above rule is 0010 as per CSS specificity. The same way, if there are two classes:

.class1.class2 {}
.class1.class1 {}

Note that in the second line, I have written twice the same class. Both will be computed to 0020, which is higher than the first one, in spite of the "unknown" class, we have two classes in the rule now.

This is the same trick I used in the above example to make the theming easier.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252