...">

Question about CSS ordering rules

Why does the following code result in red instead of 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 will turn black as expected. Why is this?

+4
source share
3 answers

Because in CSS, specificity also applies to cascading.

[att=A].classA sets the attribute and class name.

.error is for class name only

Since the former is more specific, it is applied over the latter.

If you want to force an override of a previously applied style, you can use the !important declaration:

 [att=A].classA { background-color: red !important; } 

However, I should note that IE ignores the announcement !important buggy support for it, so use it with caution.

+4
source

This is due to CSS specifics . The red rule is more specific (elements that have this AND this class attribute) than the black rule (elements that have this class). When you delete [att=A] , they have the same specificity, but since the black rule is later in the file, it wins.

+5
source

The most specific selector wins, and [att=A].classA more specific than .error . Without it, the last CSS win declared, for example:

 .error { background-color: black; } .classA { background-color: red; } 

Will also result in red .

+4
source

Source: https://habr.com/ru/post/1313341/


All Articles