How to add transition on hover with CSS

CSS transitions allows us to change property values smoothly (from one value to another), over a given duration.

Animate an element with basic transition on hover

In the example code given below, we will make the opacity of an element change when a user hovers or mouses over the element.

Example Code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
  </head>
  <style>
    .elem {
      background: blueviolet;
      width: 300px;
      height: 150px;
    }
    .elem:hover {
      opacity: 0.5;
    }
  </style>
  <body>
    <div class="elem"></div>
  </body>
</html>

This is a simple transition that can be triggered when we hover over the element. We can add more than one transition that will run at the same time.

Let’s add a scale transform property to add scale transition to the element.

.elem:hover {
       transform: scale(1.1);     
}

But the transition doesn’t seem to be smooth, because we didn’t define the duration of the transition or use any timing function.

If we add the transition property, it will make the element move more smoothly.

.elem {
  background: blueviolet;
  width: 300px;
  height: 150px;
  margin: 20px auto;
  transition: 500ms linear; 
}

Let’s break down how the transition property works:

transition: 500ms linear;
->500ms: the duration of the transition in milliseconds
->linear: the timing-function

div {
  transition: <property> <duration> <timing-function> <delay>;
}

We can add more options like below:

delay {
 transition-property: font-size;
   transition-duration: 4s;
   transition-delay: 2s;
 }

transition-property: the property you want to animate. It can be any CSS element like background, height, translateY, translateX, and so on.
transition-duration: the duration of the transition.
transition-delay: the delay before the transition starts.

Leave a comment

Your email address will not be published. Required fields are marked *