Page 91 - CSS
P. 91
!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.
A final note
A common misconception about CSS specificity is that the Group A, B and c values should be
combined with each other (a=1, b=5, c=1 => 151). This is not the case. If this were the case,
having 20 of a Group B or c selector would be enough to override a single Group A or B selector
respectively. The three groups should be regarded as individual levels of specificity. Specificity
cannot be represented by a single value.
When creating your CSS style sheet, you should maintain the lowest specificity as possible. If you
need to make the specificity a little higher to overwrite another method, make it higher but as low
as possible to make it higher. You shouldn't need to have a selector like this:
body.page header.container nav div#main-nav li a {}
This makes future changes harder and pollutes that css page.
You can calculate the specificity of your selector here
More complex specificity example
div {
font-size: 7px;
border: 3px dotted pink;
background-color: yellow;
color: purple;
}
body.mystyle > div.myotherstyle {
font-size: 11px;
https://riptutorial.com/ 69

