Reputation: 171341
Why the following code results in red color rather than black ?
HTML:
<div class="error classA" att="A"></div>
CSS:
div {
width: 100px;
height: 100px;
}
[att=A].classA {
background-color: red;
}
.error {
background-color: black;
}
If I remove [att=A]
, it becomes black, as expected. Why is that ?
Upvotes: 4
Views: 251
Reputation: 27436
Because in CSS, specificity counts towards the "Cascade" too.
[att=A].classA
targets an attribute and a class name.
.error
only targets a class name
Because the first is more specific, it gets applied over top of the second.
If you want to forcefully override a previously applied style, you can use the !important
declaration:
[att=A].classA {
background-color: red !important;
}
However, I should note, IE ignores the has buggy support for it, so use it with care.!important
declaration
Upvotes: 4
Reputation: 630409
The most specific selector wins, and [att=A].classA
is more specific than .error
. Without it, the last one declared in the CSS wins, for example:
.error {
background-color: black;
}
.classA {
background-color: red;
}
Would also result in red
.
Upvotes: 4
Reputation: 546045
It's because of CSS Specificity. The 'red' rule is more specific (elements which have this attribute AND this class) than the 'black' rule (elements which have this class). When you remove the [att=A]
, they have the same specificity, but because the black rule is later in the file, it wins.
Upvotes: 5