DEV Community

Discussion on: 10 Must CSS tricks and tips for beginners

Collapse
 
gsarig profile image
Giorgos Sarigiannidis • Edited

Use of !important should be discouraged. Instead, if you want to override a previously declared style, you can make the selector more specific. For example, suppose we have this markup:

<div class="container">
   <p class="element">Some text</p>
</div>
Enter fullscreen mode Exit fullscreen mode

To override the styles assigned to .element, it is better to do this:

.container .element {
   color: #000;
}
Enter fullscreen mode Exit fullscreen mode

or

p.element {
   color: #000;
}
Enter fullscreen mode Exit fullscreen mode

instead of that:

.element {
   color: #000 !important;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rahxuls profile image
Rahul

That's comfortable to you.

Collapse
 
gsarig profile image
Giorgos Sarigiannidis • Edited

It's not about comfort or convenience, as use of !important is considered a bad practice and should be avoided. Quoting from MDN:

Using !important, however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets. When two conflicting declarations with the !important rule are applied to the same element, the declaration with a greater specificity will be applied.

It's good for novice developers to know that !important exists, as they might eventually need it at some point, but they should also know that it should be the last resort.

Thread Thread
 
rahxuls profile image
Rahul

Sure. This is cool and must know.

Collapse
 
alexbricepalo profile image
Alex Brice

The need for !important is usually a sign of poorly written code.