Use of !important within CSS

Hi all

So I’m expiermenting with the parallex effect on the codepen project below.

Everything seems to be working as i want, but the code ive been using makes use of the !improtant tag which I thought was seen as bad practice.

Is there something I should change on my code instead using the !important tag? or should I stick with it seen as it works.

I’m hoping to eventually add this project to a future portfolio so i wan’t to avoid things that may be seen as bad practice.

Thanks fellow coders!

Well, it’s because the background images are being set inline in the HTML. If you set them in the CSS you don’t need the !important.

As a general rule using !important is not something you want to do unless you have a good reason for it. Fighting specificity because of poorly organized CSS or poorly chosen selectors is not the right use of !important. However, there are plenty of perfectly valid and useful reasons for using it. Like utility styles or other controlled and specific overwrite needs.

1 Like

Thank you @lasjorg for the help!

I forgot about the inline style overriding everything else. I have now changed the code and put the background class within the CSS.

Thanks again, its really appreciated!

Using !important is a bit of the CSS version of making a deal with the devil.

1 Like

A good use of using it would to be to overwrite inline styling. ie., touchmove events.

But even then., give it to a single class that can be added and removed. Avoid assigning as a property to an actual DOM element.

.hide_me {
   display: none !important;

In this example,. if an element has hide_me class it will always be hidden. Other than that,. there’s really no reason to use it.

1 Like