Multiple !important class declarations and precedence

Css

Css Problem Overview


Theoretically speaking, if you had this scenario:

<style type="text/css">
	.class1 {
		color:#F00 !important;
	}
	.class2 {
		color:#00F !important;
	}
</style>

<p class="class2 class1">Test</p>

Which color should take precedence? How do browsers determine precedence in this scenario?

Css Solutions


Solution 1 - Css

According to this source: http://www.boogiejack.com/CSS_4.html

class2 should override the class1 styling.

> Order of Specification: As a last > resort, when all other conflict > resolution specifications cannot > determine which style should take > precedence, the last style specified > will be the style used.

Solution 2 - Css

With two equally weighted selectors, the behavior is the same whether you apply !important to both or omit it from both.

<style type="text/css">
    .class1 {
        color: #F00; /* red */
    }
    .class2 {
        color: #00F; /* blue */
    }
</style>

The order of classes in the html class attribute is irrespective of each class selector's specificity level.

<p class="class2 class1">Test X</p>
<p class="class1 class2">Test Y</p>

Output

  • Test X → blue
  • Test Y → blue

If you use !important on just one selector class, then that one will take precedence (because it takes on a higher level of specificity).

Solution 3 - Css

Since classes are all "equal important" when added to an element it doesn't matter in which order you assign them to your paragraph.

In this case, color in .class1 and .class2 are both declared as important, but because .class2 was declared after .class1 the browser will show your paragraph in blue, since it overwrites the declared color from .class1

Also, have a look at this: http://jsfiddle.net/3uPXx/1/ You can see it doesn't matter in which order you declare the class on your paragraph. Since both classes define the same attribute (color) it will be overwritten be the class which is declared last.

The only thing that can overwrite this is an inline-style with !important as you can see in the fiddle.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen DyerView Question on Stackoverflow
Solution 1 - CssJan_VView Answer on Stackoverflow
Solution 2 - CsssmilyfaceView Answer on Stackoverflow
Solution 3 - CssTimView Answer on Stackoverflow