How to animate buttons using CSS?


To animate buttons on a web page, use the transition property. Set the transition duration as well. Using the :after selector on a button, set how the look of the button animates after it is clicked.

Create a Button

Let us first create a button using the <button> element −

<button>Click Here</button>

Style the Button

The button is styled here. The position is set to relative, the cursor is set to pointer. With that, the width is also set −

button {
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   position: relative;
   background-color: rgb(100, 0, 84);
   border: none;
   font-size: 28px;
   color: rgb(255, 169, 255);
   padding: 20px;
   width: 200px;
   text-align: center;
   box-shadow: 5px 10px 18px rgb(121, 82, 185);
   text-decoration: none;
   overflow: hidden;
   cursor: pointer;
}

Animate the Button When it is Clicked

The transition property is used to set the animation immediately when the button is clicked. The transition duration is set to 0.8 seconds −

button:after {
   content: "";
   background: rgb(251, 255, 0);
   display: block;
   position: absolute;
   padding-top: 300%;
   padding-left: 350%;
   margin-left: -20px;
   margin-top: -120%;
   opacity: 0;
   transition: all 0.8s
}

Style the Button When it is Active

The :active selector is used to select and style a button when it is active −

button:active:after {
   padding: 0;
   margin: 0;
   opacity: 1;
   transition: 0s
}

Example

The following is the code to animate buttons with CSS −

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <style>
      button {
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         position: relative;
         background-color: rgb(100, 0, 84);
         border: none;
         font-size: 28px;
         color: rgb(255, 169, 255);
         padding: 20px;
         width: 200px;
         text-align: center;
         box-shadow: 5px 10px 18px rgb(121, 82, 185);
         text-decoration: none;
         overflow: hidden;
         cursor: pointer;
      }
      button:after {
         content: "";
         background: rgb(251, 255, 0);
         display: block;
         position: absolute;
         padding-top: 300%;
         padding-left: 350%;
         margin-left: -20px;
         margin-top: -120%;
         opacity: 0;
         transition: all 0.8s
      }
      button:active:after {
         padding: 0;
         margin: 0;
         opacity: 1;
         transition: 0s
      }
   </style>
</head>
<body>
   <h1>Animated Button Example</h1>
   <button>Click Here</button>
   <p>Click on the above button to see ripple effect</p>
</body>
</html>

Updated on: 15-Nov-2023

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements