DEV Community

Cover image for Linear Gradient Animation in CSS
Ustariz Enzo
Ustariz Enzo

Posted on • Edited on

Linear Gradient Animation in CSS

Hey fellow creators

You can’t really create a hover animation between two linear gradients in CSS, but there’s a way around it... Let’s learn what it is in less than a minute!

Gradient animation

If you prefer to watch the video version, it's right here :

 

1. The HTML structure.

Create a card with a title:



<div class="card">
      <div class="layer"></div>
      <h1>São Paulo</h1>
</div>


Enter fullscreen mode Exit fullscreen mode

 

2. Style the card.

 
Give the card a width and a height, center it and its content and add a background:



.card {
  width: 400px;
  height: 400px;
  border-radius: 25px;
  margin: 100px auto;
  position: relative;
  z-index: 1;
  background: linear-gradient(to right, #2193b0, #6dd5ed); 
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.card h1 {
  color: #f1f1f1;
  font-size: 50px;
  text-transform: uppercase;
}


Enter fullscreen mode Exit fullscreen mode

 
Create a new layer with the pseudo-element after:



.card::after {
  content:"";
  width: 100%;
  height: 100%;
  border-radius: 25px;
  background: linear-gradient(to right, #8a2387, #e94057, #f27121);
  position: absolute;
  z-index: -1;
  opacity: 0;
  transition: opacity 0.4s ease-in-out;
}


Enter fullscreen mode Exit fullscreen mode

It will take up the whole size of the card but with a new color. It will be located between the content and the container. It has no opacity for now.

 
Finally, add a different opacity to the pseudo element when you hover the card:



.card:hover::after {
  opacity: 1;
}


Enter fullscreen mode Exit fullscreen mode

 
Now you have a transition between your two linear gradients! Check out source code here to see the final outcome!

 
Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

See you soon!

Enzo.

Top comments (0)