DEV Community

Cover image for About !Important, the CSS Rule ...
Adejokun Ibukunoluwa
Adejokun Ibukunoluwa

Posted on

About !Important, the CSS Rule ...

"Where there is great power there is great responsibility" - Winston Churchill(1906)

When debugging stylesheets, developers tend to misuse this (!Important value) power, which could be due to several reasons such as laziness, frustration or even deadlines and so on, forgetting about the rule of specificity.

The Rule of Specificity

The rule of specificity follows a hierarchy, There are four categories which define the specificity level of a selector:

  1. Inline styles - Example: <h1 style="color: pink;">
  2. IDs - Example: #navbar
  3. Classes, pseudo-classes, attribute selectors - Example: .test, :hover, [href]
  4. Elements and pseudo-elements - Example: h1, :before

Possible uses cases of the !important rule

1.The !important rule are very useful in cases such as Custom user style sheets where users can make quick edits with the help of the browser to modify the style sheet to suit the user's needs.
2.The use of !important in Javascript syntax.

Why you should not use !important

1.damages the code,
2.makes debugging hard and
3.Time exhausting especially on large projects;

It is recommended for use only as a last resort or it should not be used at all.

How to override !important

As curated from the mozilla developer documentation (https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) it can be overridden by:

1.Adding another CSS rule with !important, and either give the selector a higher specificity (adding a tag, id or class to the selector), or add a CSS rule with the same selector at a later point than the existing one. This works because in a specificity tie, the last rule defined wins.

table td    { height: 50px !important; }
.myTable td { height: 50px !important; }
#myTable td { height: 50px !important; }
Enter fullscreen mode Exit fullscreen mode


#myTable td gets executed due to specificity rule

2.Refactoring the Code and removing every use of !important in the source code.

Hope this helps 😉.
Don't forget to like my post 😁💗 and If you have any feedback or questions, don't hesitate to comment below.

Top comments (0)