Burger Menu Icon Animation

Categories: Code

Tags: , ,

I am going to show you how to add a simple animation effect to the burger menu icon.

The burger menu icon has become so popular as more people browse the internet on their mobile devices. There are so many variations of animating the burger menu icon. I am going to show you possibly the easiest one. We’re going to use HTML, CSS and a very simple jQuery. Let’s start cooking.

Firstly, we need to create the burger menu icon using HTML and CSS.

1
2
3
4
<div class="sample-menu-button">
  <div class="sample-menu-icon">
  </div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
.sample-menu-button {
  width: 100px;
  height: 100px;
  background-color: DeepSkyBlue;
  cursor: pointer;
}
.sample-menu-icon {
  position: absolute;
  top: 50%;
  left: 20%;
  height: 4px;
  margin-top: -2px;
  right: 0;
  width: 60%;
}
.sample-menu-icon::before,
.sample-menu-icon::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  height: 4px;
}
.sample-menu-icon::before {
  top: -24px;
}
.sample-menu-icon::after {
  bottom: -24px;
}
.sample-menu-icon,
.sample-menu-icon::before,
.sample-menu-icon::after {
  background-color: white;
}

Next, we need to add a class to the button when clicked using a simple jQuery code.

1
2
3
$('.sample-menu-button').click(function() {
  $(this).toggleClass('active');
});

Now, we can add the animation effect to the button with ‘active’ class.

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
.sample-menu-button:hover,
.sample-menu-button.active {
  background-color: RoyalBlue;
}
.sample-menu-button.active:hover {
  background-color: DeepSkyBlue;
}
.sample-menu-button.active .sample-menu-icon {
  left: 10%;
  width: 80%;
  background-color: transparent;
}
.sample-menu-button.active .sample-menu-icon::before,
.sample-menu-button.active .sample-menu-icon::after {
  top: 50%;
  margin-top: -2px;
}
.sample-menu-button.active .sample-menu-icon::before {
  transform: rotate(45deg);
}
.sample-menu-button.active .sample-menu-icon::after {
  transform: rotate(-45deg);
}

When you click the button, the burger menu icon should turn to close ‘X’ icon. However it doesn’t animate smoothly yet. The missing secret ingredient is CSS transition. Add it to ‘sample-menu-icon’, ‘.sample-menu-icon::before’ and ‘.sample-menu-icon::after’ classes.

30
31
32
33
34
35
.sample-menu-icon,
.sample-menu-icon::before,
.sample-menu-icon::after {
  background-color: white;
  transition: all 0.3s ease-in-out;}

The result would be like below.

For the smooth colour transition, add the CSS transition to CSS line 1.

1
2
3
4
5
6
7
.sample-menu-button {
  width: 100px;
  height: 100px;
  background-color: DeepSkyBlue;
  transition: all 0.3s ease-in-out;  cursor: pointer;
}

You can also see it in action at my CodePen page.

See the Pen Burger Menu Animation by WebMadeWell (@webmadewell) on CodePen.