The !important declaration is used too much in modern CSS. If you write proper lean and clean CSS, and target the right classes, you won’t have to use the declaration, and put future you in a pickle.
The !important
declaration in CSS is used to override any previously declared style rules for a particular element. While it can be useful in certain situations, it is generally recommended to avoid using !important
as much as possible.
!important
CSS selectors have a hierarchy of specificity, which determines which styles are applied to an element when multiple conflicting styles are defined. When you use !important
, you’re essentially jumping to the top of this hierarchy and overriding all other styles, which can make it harder to predict how your styles will behave.
Using !important
can make it more difficult to maintain your code in the future.
If you have multiple stylesheets or developers working on the same codebase, it can be difficult to remember which styles are !important
and which aren’t, leading to potential conflicts and errors.
When you use !important
, you’re essentially telling the browser to disregard any other styles that may be applied to an element, even those that are important for accessibility or responsive design.
A good example on how to bypass Bootstrap without using !important
is found in the .navbar
.
The .navbar
navigation usually looks something like this:
<nav class="navbar navbar-expand-lg">
<div class="container">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
Styling the nav links would require us to target .nav-link
.
.nav-link {
font-family: 'Montserrat', sans-serif;
font-size: 1rem;
color: #787878;
}
Normally you would like to add padding
here as well, but that wouldn’t work. And the reason why, is because the padding is handled by .navbar-expand-lg .navbar-nav .nav-link
, since it’s determined by the .navbar-expand-lg
.
Therefor, I would have to do the following, in order to not use !important
.
.navbar-expand-lg .navbar-nav .nav-link {
padding-right: 1rem;
padding-left: 1rem;
}
There may be situations where using !important
is necessary, it should be used sparingly and only when other solutions have been exhausted.
!important
can be a needed tool, if you have to override inline css from a third-party.
However, it’s generally better to write well-structured, maintainable CSS that follows the rules of specificity and cascading, rather than relying on “!important” as a quick fix.
This can lead to unpredictable behavior and make it harder to create consistent, well-designed interfaces.