tags:

views:

48

answers:

3

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 ?

+5  A: 

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.

nickf
Thanks a lot ! I didn't know about specificity. I thought that always the last rule wins.
Misha Moroshko
+4  A: 

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.

Nick Craver
+4  A: 

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 !important declarationhas buggy support for it, so use it with care.

Austin Hyde
Thanks for the "!important". I didn't know about that.
Misha Moroshko
IE does not ignore `!important`.
nickf
Sorry, you're right, nickf. My original source was outdated, and I haven't used it for awhile. I've fixed with a link to current support.
Austin Hyde