How to Read !Important in CSS

How do you read !important in CSS?

an "!important" declaration (the delimiter token "!" and keyword
"important" follow the declaration) takes precedence over a normal
declaration.

http://www.w3.org/TR/CSS2/cascade.html#important-rules

Basically, where two style rules are the same... it gives the one marked !important greater importance and will apply those styles.

Example

div{
opacity:0 !important;
}

div.jason{
opacity:1;
}

The first rule would be applied even though the second rule is more specific (one element + one class as opposed to one element)

Note: IE6 ignores !important when you have two of the same property and one of them is important - it'll always apply the last declaration, whether or not it was marked important. **Added from @BoltClock's comment below.

Warning: !important is a hammer that should only be used when absolutely necessary. Almost always, it is better to use more specific selectors to achieve greater specificity and have your styles applied the way you want. !important can make it very difficult for future developers to find and make changes to your code.

One good use case: !important is great for user-defined styles, where a user wants to manipulate Web site pages in specific way in his browser (say make all the backgrounds black and the text yellow). Without having to worry about specificity, the user can add styles to certain elements (like body) and make the styles render.

What does !important mean in CSS?

It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'

In normal use a rule defined in an external stylesheet is overruled by a style defined in the head of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important 'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.

Also, ordinarily, a more specific rule will override a less-specific rule. So:

a {
/* css */
}

Is normally overruled by:

body div #elementID ul li a {
/* css */
}

As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.

If, however, you add !important to the less-specific selector's CSS declaration, it will have priority.

Using !important has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.

It also makes debugging your CSS a nightmare (from personal, empirical, experience).

What are the implications of using !important in CSS?

Yes, I'd say your example of using !important is bad practice, and it's very likely it would cause undesired effects further down the line. That doesn't mean it's never okay to use though.

What's wrong with !important:

Specificity is one of the main forces at work when the browser decides how CSS affects the page. The more specific a selector is, the more importance is added to it. This usually coincides with how often the selected element occurs. For example:

button { 
color: black;
}
button.highlight {
color: blue;
font-size: 1.5em;
}
button#buyNow {
color: green;
font-size: 2em;
}

On this page, all buttons are black. Except the buttons with the class "highlight", which are blue. Except that one unique button with the ID "buyNow", which is green. The importance of the entire rule (both the color and font-size in this case) is managed by the specificity of the selector.

!important, however, is added at a property level, not a selector level. If, for instance, we used this rule:

button.highlight {
color: blue !important;
font-size: 1.5em;
}

then the color property would have a higher importance than the font-size. In fact, the color is more important than the color in the button#buyNow selector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).

An element <button class="highlight" id="buyNow"> would have a font-size of 2em, but a color blue.

This means two things:

  1. The selector does not accurately convey the importance of all the rules inside it
  2. The only way to override the color blue is to use another !important declaration, for example in the button#buyNow selector.

This not only makes your stylesheets a lot harder to maintain and debug, it starts a snowball effect. One !important leads to another to override it, to yet another to override that, et cetera. It almost never stays with just one. Even though one !important can be a useful short-term solution, it will come back to bite you in the ass in the long run.

When is it okay to use:

  • Overriding styles in a user stylesheet.

This is what !important was invented for in the first place: to give the user a means to override website styles. It's used a lot by accessibility tools like screen readers, ad blockers, and more.

  • Overriding 3rd party code & inline styles.

Generally I'd say this is a case of code smell, but sometimes you just have no option. As a developer, you should aim to have as much control over your code as possible, but there are cases when your hands are tied and you just have to work with whatever is present. Use !important sparingly.

  • Utility classes

Many libraries and frameworks come with utility classes like .hidden, .error, or .clearfix. They serve a single purpose, and often apply very few, but very important, rules. (display: none for a .hidden class, for example). These should override whatever other styles are currently on the element, and definitely warrant an !important if you ask me.

Conclusion

Using the !important declaration is often considered bad practice because it has side effects that mess with one of CSS's core mechanisms: specificity. In many cases, using it could indicate poor CSS architecture.

There are cases in which it's tolerable or even preferred, but make sure you double check that one of those cases actually applies to your situation before using it.

CSS !important not working

Give the <div> an id and then add this rule to your CSS stylesheet (or in a <style> tag if you don't want to change the style sheet):

#your_div_id span {
font-family : calibri; font-size: 20pt !important;
}

!important in CSS allows the author to override inline styles (since they have a higher precedence than style sheet styles normally). It doesn't automatically make the style marked !important override everything else.

SEE: The W3C's documentation on CSS Selector Specificity.

Felix's Demo of the markup

understanding css important keyword in this example

It's a.readMore instead of .readMore a (the first case would search for an element with class .readMore and append the CSS to any children a-elements)

and #mainNewsBody .news should be #mainNewsBody.news (you should 'concatenate' the id and class since they refer to the same element)

making a total of #mainNewsBody.news a.readMore

Fiddle

EDIT

I see many notes on simplifying your css to just classes. This really depends on what you're trying to accomplish. If you're working with a huge CSS file, I'd recommend specifying as strict as possible. This to prevent any CSS being applied on places where you don't want it to.

a { } for example will mess with all your links, a.news { } will only mess with a class='news'

Why do I have to use the !important in this case?

Be more specific with your css and remove all your !importants:

.parent div.child {
width: 50%;
height: 50px;
}

should work just fine

External CSS !important overriding inline !important

You have apparently confused inline style origin that originates from physical HTML attribute (<el style="[css declarations]">) with in-page style sheet that has "author" level origin specificity and originates either from <style>[css rules]</style> or <link rel="stylesheet" href="[css file url]">.

Style and link elements in page are origin-wise equal, attribute is more origin-wise specific.

It is not possible to beat !important rules from inline origin level (attribute) with !important rule from author level origin.

How to apply !important using .css()?

Most of these answers are now outdated, IE7 support is not an issue.

The best way to do this that supports IE11+ and all modern browsers is:

const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');

Or if you want, you can create a small jQuery plugin that does this.
This plugin closely matches jQuery's own css() method in the parameters it supports:

/**
* Sets a CSS style on the selected element(s) with !important priority.
* This supports camelCased CSS style property names and calling with an object
* like the jQuery `css()` method.
* Unlike jQuery's css() this does NOT work as a getter.
*
* @param {string|Object<string, string>} name
* @param {string|undefined} value
*/
jQuery.fn.cssImportant = function(name, value) {
const $this = this;
const applyStyles = (n, v) => {
// Convert style name from camelCase to dashed-case.
const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
return m1 + "-" + upper.toLowerCase() + m2;
});
// Loop over each element in the selector and set the styles.
$this.each(function(){
this.style.setProperty(dashedName, v, 'important');
});
};
// If called with the first parameter that is an object,
// Loop over the entries in the object and apply those styles.
if(jQuery.isPlainObject(name)){
for(const [n, v] of Object.entries(name)){
applyStyles(n, v);
}
} else {
// Otherwise called with style name and value.
applyStyles(name, value);
}
// This is required for making jQuery plugin calls chainable.
return $this;
};
// Call the new plugin:
$('#elem').cssImportant('height', '100px');

// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});

// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');

Example jsfiddle here.



Related Topics



Leave a reply



Submit