Home > Enterprise >  CSS: define animations inline without a separate `keyframes` class
CSS: define animations inline without a separate `keyframes` class

Time:05-22

Generally you would define a onHover animation of a square class like this:

.square:hover {
  animation-duration: 0.5s;
  animation-name: square_hover;
}

@keyframes square_hover {
  to {background-color: yellow;}
}

Is there a way to define it like this:

.square:hover {
  animation-duration: 0.5s;
  animation: {
    to { background-color: yellow; }
  };
}

@keyframes square_hover 

?

CodePudding user response:

According to MDN the correct way of declaring an animation is using this syntax:

@keyframes <keyframes-name> {
  <keyframe-block-list>
}

And then call it back using animation properties:

animation-duration: time;
animation-name: animation;

Where you will is a string that will identify the animation name. And is the sequence you will follow to create the animation.

So in short, CSS has a strict syntax you have to follow. But it seems like you're trying to find a simpler way to declare/create animation on hover.

You can simply get rid of the animation and directly add the properties you want to change on hover. For instance, if you want to change the background colour of the square class you will simply start with the initial state/base styles:

.square {
  background-color: black;
}

And then apply the styles you want to change:

.square:hover {
  background-color: yellow;
}

And if you want smooth out the transition simply add the transition property to the base styles. And the syntax looks something like

transition: property-to-transition time ease;

A working example:

.square {
  background-color: black;
  transition: background-color .5s ease;
}

References:

MDN Docs @keyframes: @keyframes

MDN Docs transitions: transitions

MDN Docs animations: animations

  •  Tags:  
  • css
  • Related