Let’s say I have two CSS classes:
.all {
background-color: red;
border: 5px solid black;
}
.some {
background-color: blue;
}
Some HTML elements will have the attribute class="all some"
(i.e. they will have both classes). In this case, I want the class some
to override all
(the element should appear blue, but still have a 5px black border). What is the most efficient way to do this, without using the !important
keyword? I have used this for a while, and it works (notice the [class]
specifier on the some
rule):
.all {
background-color: red;
border: 5px solid black;
}
.some[class] {
background-color: blue;
}
Is there a special "precedence" character in CSS made for situations like this?
Note: there is no guarantee that some
will always come after all
in the stylesheets.
2
Answers
You can declare styles for elements with multiple classes. Like this
The way it determines which to use is related to the specificity, also see this for more examples
For a better way than hacking the specificity, you need cascade layers.
You can’t raise the precedence of
.some
, but you can lower the precedence of.all
. Do this: