CSS Cascading and Specificity
Each individual CSS Selector has its own specificity value. Every selector in a sequence increases the sequence's overall specificity. Selectors fall into one of three different specificity groups: A, B and c. When multiple selector sequences select a given element, the browser uses the styles applied by the sequence with the highest overall specificity.
- id selectors - #foo
- class selectors - .bar
- attribute selectors - [title], [colspan="2"]
- type selectors - div, li
The universal selector (*) and combinators (like > and ~) have no specificity.
Here we have an ID selector which declares color as blue, and a class selector which declares color as red and background as black.An element with an ID of #foo and a class of .bar will be selected by both declarations. ID selectors have a Group A specificity and class selectors have a Group B specificity. An ID selector outweighs any number of class selectors. Because of this, color:blue; from the #foo selector and the background:black; from the .bar selector will be applied to the element. The higher specificity of the ID selector will cause the browser to ignore the .bar selector's color declaration.
Here we have two class selectors; one of which declares color as red and background as black, and the other declares background as white.An element with both the .bar and .baz classes will be affected by both of these declarations, however the problem we have now is that both .bar and .baz have an identical Group B specificity. The cascading nature of CSS resolves this for us: as .baz is defined after .bar, our element ends up with the red color from .bar but the white background from .baz.
!important and inline style declarations
The !important flag on a style declaration and styles declared by the HTML style attribute are considered to have a greater specificity than any selector. If these exist, the style declaration they affect will overrule other declarations regardless of their specificity. That is, unless you have more than one declaration that contains an !important flag for the same property that apply to the same element. Then, normal specificity rules will apply to those properties in reference to each other.Because they completely override specificity, the use of !important is frowned upon in most use cases. One should use it as little as possible. To keep CSS code efficient and maintainable in the long run, it's almost always better to increase the specificity of the surrounding selector than to use !important. One of those rare exceptions where !important is not frowned upon, is when implementing generic helper classes like a .hidden or .background-yellow class that are supposed to always override one or more properties wherever they are encountered. And even then, you need to know what you're doing. The last thing you want, when writing maintainable CSS, is to have !important flags throughout your CSS.