Adding Click Animation to a Button with CSS: A Step-by-Step Tutorial
Tags: css, frontend, beginners, tutorial
Published: 2024-01-24 22:14:10

If you are just starting with CSS, this guide will walk you through the basics of animation, explaining each concept in details. After looking at basics, we will use one of the approaches to add click animation to a button.

### **Understanding CSS Animation**

In the world of web development, CSS animation serves as a powerful tool to make your interface dynamic and engaging. Let's discuss the two fundamental methods of CSS animation: transitions and keyframes.

### Transitions:

**What are Transitions?**
Transitions offer a straightforward and intuitive approach to animating changes in CSS properties. This is a smooth effect, where an element is being changed from one state to another over a specified duration.

**How Do Transitions Work?**
Transitions work by defining the starting and ending states of an element. When a change occurs (like a hover or a click), the transition property steps in, smoothly interpolating between the old and new states. This is achieved by specifying the property to be transitioned, the duration of the transition, and the timing function defining the pace of the change.

```css
/* Adding a transition to the width property */
.btn {
  width: 200px;
  transition: width 0.5s ease; 
  /* 
  width - the property that will be animated
  0.5 - duration in seconds
  ease - timing function 
  */
}

.btn:hover {
  width: 250px; /* New width on hover */
}

```

In this example, the button's width changes smoothly from 200px to 250px over 0.5 seconds when hovered.

### Keyframes:

**What are Keyframes?**
Keyframes provide a more detailed control over the animation process. They allow you to define specific points (keyframes) in an animation sequence, each representing a unique state of the element.

**How Do Keyframes Work?**
You set up keyframes at different intervals, specifying the styles for each of them. The browser transitions between these keyframes, creating a more complex and customized animation sequence.

```css
/* Defining keyframes for a bouncing animation */
@keyframes bounce {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
  100% {
    transform: translateY(0);
  }
}

/* Applying the keyframe animation to an element */
.element {
  animation: bounce 2s infinite; 
  /* Bouncing animation lasting 2 seconds, repeating infinitely */
}

```

In this example, the element will smoothly bounce up and down in a loop.

### Choosing Between Transitions and Keyframes:

When deciding between transitions and keyframes, consider which effect do you want to achieve. Transitions are perfect for simple effects, like hovering over a button, while keyframes are preferable when creating more dynamic and complex animations, when you need more control.


### **`transition` and `transform` properties**

Now, let's take a closer look at the specific CSS properties we will be using in the tutorial – **`transition`** and **`transform`**. Understanding how these properties work will empower your control of the animations.

**`transition`:**

**What is it?**
The transition property is a fundamental tool for facilitating smooth changes in CSS properties over a specified duration.
**How does it work?**
In the example below, we use **`transition`** to set the animation's duration and easing function. The **`duration`** determines how long the transition takes, while the **`easing function`** influences the speed variations throughout the animation.
        
```css
.btn {
  width: 200px;
  transition: width 3s ease; /* Duration: 3 seconds with an ease timing function */
}
        
.btn:hover {
  width: 250px; /* New width on hover */
}
```
        
In this example, the button smoothly transitions its width over 3 seconds with an ease timing function.
        
**`transform`:**

**What is it?**
The `transform` property is a great tool that enables two-dimensional and three-dimensional transformations in CSS. It provides functionalities like rotation, scaling, skewing, or translating elements, allowing for dynamic adjustments in their appearance and position.
**How does it work?**
In the example below, we use **`transform`** to give the checkmark icon a dynamic movement. By using **`translate`** in combination with **`opacity`**, we create a visually appealing transformation when the icon appears.
        
```css
.icon {
  opacity: 0;
  transition: transform 2s ease, opacity 2s ease 3s;
}
        
.icon.done {
  opacity: 1;
  transform: translate(-50%, -180%);
}
        
```
        
In this example, the icon smoothly translates upwards and becomes visible over 2 seconds, with a delay of 3 seconds.
        
### **Let's add a click animation to a button**
### Breaking Down the Requirements:

1. We will create a button with a rounded border and some text inside.
2. When the user clicks on it, we want the text to disappear, making room for a checkmark icon.
3. As an extra touch, let's make the border gradually narrow until it forms a circle.


![the button state before click](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/93b2bj99g5e5dawzlrbq.png)


![the button state after click](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dg9a1y0ecdu1csi696ph.png)

Let’s start with HTML structure. 
We need a div wrapper, and a button and an icon inside it.

```html
<div class="wrapper">
  <button class="btn">Click on me!</button>
  <div class="icon">✔️</div>
</div>
```

Add some css styles for the button and icon.
For the button, we will be animating width and border-radius properties. Initial values of these properties we set for the class name `.btn`, and the new values for the class name `.btn.clicked`, which will be applied after clicking on the button. The same is for the icon.

```css
.wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

.btn {
  height: 40px;
  color: white;
  background: #FFB3CB;
  border: 1px solid white;
  cursor: pointer;

  width: 200px;
  border-radius: 10px;
  transition: width 3s ease, border-radius 2s ease;
}

.btn.clicked {
  color: #FFB3CB;

  width: 40px;
  border-radius: 50px;
}

.icon {	
  position: absolute;
  top: 110%;
  left: 50%;
  cursor: pointer;

  opacity: 0;
  transition: transform 2s ease, opacity 2s ease 3s;
}

.icon.done {
  opacity: 1;
  transform: translate(-50%,-180%);
}
```

Now add event listener in JS, so that the animations will be working.
We will be adding the additional classes to the button and the icon, when clicking on the button.

```js
/* choose the elements */
const button = document.querySelector(".btn");
const icon = document.querySelector(".icon");

/* add callback function, which will be executed after clicking on the button */
const callback = () => {
  button.classList.add("clicked");
  icon.classList.add("done");
};

/* add event listener */
button.addEventListener("click", callback);
```

That's it! The animation is ready. 

I have prepared a live presentation of the transition animation for you in codepen sandbox. Use this [link](https://codepen.io/vivecodes/pen/BavPyQb) to find it.

**Conclusions:**

Mastering CSS animation with the `transition` and `transform` properties provides for developers the essential tools for creative web design.
After this tutorial, transitioning between styles should feel more intuitive, empowering developers to effortlessly enhance user experiences with dynamic and engaging web animations.

If you have any questions, don't hesitate to ask me in the comments section.