CSS !important

CSS !important property in CSS is used to provide more weight (importance) than normal property. In CSS, the !important means that “this is important”, ignore all the subsequent rules, and apply !important rule and the !important keyword must be placed at the end of the line, immediately before the semicolon.

  • In other words, it adds importance to all the sub-properties that the shorthand property represents.
  • In normal use, a rule defined in an external style sheet which is overruled by a style defined in the head of the document, which in turn, is overruled by an inline style within the element itself (assuming equal specificity of the selectors).
  • Defining a rule with the !important attribute that discards the normal concerns as regards the later rule overriding the earlier ones.
  • So, it is used for overriding the styles that are previously declared in other style sources, in order to achieve a certain design.
#myid {
  background-color: green;
}

.myclass {
  background-color: orange;
}

p {
  background-color: red !important;
}

CSS !important-Important

  • When !important was first introduced in CSS1, an author rule with an !important declaration held more weight than a user rule with an !important declaration; to improve accessibility, this was reversed in CSS2
  • If !important is used on a shorthand property, this adds “importance” to all the sub-properties that the shorthand property represents
  • The !important keyword (or statement) must be placed at the end of the line, immediately before the semicolon, otherwise it will have no effect (although a space before the semicolon won’t break it)
  • If for some particular reason you have to write the same property twice in the same declaration block, then add !important to the end of the first one, the first one will have more weight in every browser except IE6 (this works as an IE6-only hack, but doesn’t invalidate your CSS)
  • In IE6 and IE7, if you use a different word in place of !important (like !hotdog), the CSS rule will still be given extra weight, while other browsers will ignore it

CSS !important-Uses

One way to use !important is if you have to override a style that cannot be overridden in any other way. This could be if you are working on a Content Management System (CMS) and cannot edit the CSS code. Then you can set some custom styles to override some of the CMS styles.

Another way to use !important is: Assume you want a special look for all buttons on a page. Here, buttons are styled with a gray background color, white text, and some padding and border

.button {
  background-color: #FF1493;
  color: white;
  padding: 6px;
  border: 2px solid black;
}