Is this a proper use case for the CSS !important rule?

Viewed 93

I am aware that !important is not recommended, and the few known use cases where it is appropriate includes when working with third party libraries such as Bootstrap. However, i would like to ask if this use case is appropriate too. Suppose i have a <div/> which i would want to animate from background-color transparent to a certain color. However, i would like to have a color change on hover too after the animation happens, but i can't seem to find a way to do it without using the !important rule. Thanks in advance!

div{
  position: absolute;
  width: 100px;
  height: 100px;
  animation: animate 4s forwards;
}

div:hover{
  background-color: blue !important;
}


@keyframes animate{
  from {
    background-color: transparent;   
  }

  to {
    background-color: maroon;
  }
}
3 Answers

Not judging if it would be an appropriate use of !important here or not, one way around in your case would be to split your animation and transition on two different elements. Note that it's quite common to do so when you want to animate and transition the same properties.

background-color even has the advantage that you can use pseudo-elements instead of a plain one.

Less talk, more code:

div{
  position: absolute;
  width: 100px;
  height: 100px;
  animation: animate 4s forwards;
}
div::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: background-color 2s;
}
div:hover::after{
  background-color: blue;
}

@keyframes animate{
  from {
    background-color: transparent;   
  }
  to {
    background-color: maroon;
  }
}
<div></div>

What I prefer to do is unsetting the property beforehand I want to customise with the bootstrap, say I want to change button's default blue colour to red, I do it using,

background-color: unset;
background-color: #ff000;

Keep in mind, the order of code matters here by a lot

Do the animation differently and don't rely on forwards

div {
  position: absolute;
  width: 100px;
  height: 100px;
  animation: animate 4s;
  background-color: maroon;
  transition: background-color 2s;
}

div:hover {
  background-color: blue;
}

@keyframes animate {
  from {
    background-color: transparent;
  }
}
<div></div>

Related