kofifus kofifus - 2 months ago 10
CSS Question

css rules multi class, how to match two out of many

A third party defined:

.c1 { ..}

I defined a rule to match both c1 and c2

.c1.c2 { ..}

For an element with class="c1 c2" my rule matches fine

However for an element with class="c1 c2 [..other classes]" my rule does not match and the third party's rule does.

How can I get my rule to match over the third party's rule in this case (without knowing in advance of the other classes and without changing the third party's rules) ?

Answer

The only absolute way to make sure your rule will take over the others is to use the !important keyword:

.c1.c2 {
    color: red !important;
}

Note that if you know a more specific selector you can use it:

.c1 {
  color: blue;
}
.c2 {
  color: pink;
}
.c1.c4 {
  color: pink !important;
}
.c1.c5 {
  color: white;
}
div .c1.c6 {
  color: gray;
}
.c1.c2 {
  color: red;
}
.c1.c3 {
  color: green;
}
<div id="a">
  <div class="c1">blue due to .c1</div>
  <div class="c1 c2">red due to .c1.c2</div>
  <div class="c1 c2 c3">yellow due to .c1.c3</div>
  <div class="c1 c2 c3" style="color: black;">black due to inline style</div>
  <div class="c1 c2 c4">pink only because of the !important</div>
  <div class="c1 c2 c5">red becuase .c1.c2 is after .c1.c5 in the css</div>
  <div class="c1 c2 c6">gray only of more specific selector (div .c1.c5)</div>
</div>

Comments