Burger menu animation with CSS and JavaScript

By xhuljan 08 January 2021 3K 0

In this blog you will learn how to animate a burger menu with pure CSS and JavaScript.

First let's create a burger in HTML.

		<div class="burger-menu">
	<div class="burger-line"></div>
	<div class="burger-line"></div>
	<div class="burger-line"></div>
</div>

And here is the style for burger menu.

.burger-menu {
	display: inline-block;
	width: 25px;
    cursor: pointer;
}
.burger-line {
	height: 3px;
    margin-bottom: 3px;
    background: #4d4d4d;
    transition: all .4s ease /* important for animation */
}

The HTML and CSS code above will create this burger: 

To animate the burgers line we need to toggle a class on burger-menu click with JavaScript and add another CSS code for animation.

For click event we can use this pure JavaScript code:

let element = document.getElementsByClassName("burger-menu")[0];
element.onclick = function() {
	this.classList.toggle("active");
}

We are just toggling active class on burger-menu element and now we just need to add the CSS animation:

.burger-menu.active .burger-line:last-child {
	opacity: 0;
}
.burger-menu.active .burger-line:first-child {
	transform: rotate(45deg) translate(4px, 4px);
}
.burger-menu.active .burger-line:nth-child(2) {
	transform: rotate(-45deg);
}

You can find the complete example here: codepen.io/xhuljan123/pen/rNMJrOd