The hamburger icon is simply a symbol that has come to mean "menu". It's used to toggle a menu or navigation bar between being collapsed behind the button or displayed on the screen.
Here is how to create it-
1. HTML File
We start by creating our HTML file and initializing two classes to target our elements.
<body>
<div class="menu-btn">
<div class="menu-btn__burger"></div>
</div>
</body>
2. CSS File
Here we start creating and designing our hamburger icon. We start with basic properties such as defining the width, height and the transition. This creates the basic outline of the box.
.menu-btn {
position: relative;
display: flex;
justify-content: center;
align-items: center;
width: 80px;
height: 80px;
cursor: pointer;
transition: all .5s ease-in-out;
border: 3px solid #fff;
}
To get the middle line (out of the three) of our icon we define width, height and border radius as follows-
.menu-btn__burger {
width: 50px;
height: 6px;
background: #fff;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(255,101,47,.2);
transition: all .5s ease-in-out;
}
To get the other two top and bottom lines-
.menu-btn__burger::before,
.menu-btn__burger::after {
content: '';
position: absolute;
width: 50px;
height: 6px;
background: #fff;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(255,101,47,.2);
transition: all .5s ease-in-out;
}
.menu-btn__burger::before {
transform: translateY(-16px);
}
.menu-btn__burger::after {
transform: translateY(16px);
}
3. JS File
Here we work with the animation of the hamburger icon. We target the "menu-btn" class and initialize a variable "menuopen" to be false. We add an eventListener "click" which either adds or removes the class "open".
const menuBtn = document.querySelector('.menu-btn');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
if(!menuOpen) {
menuBtn.classList.add('open');
menuOpen = true;
} else {
menuBtn.classList.remove('open');
menuOpen = false;
}
});
4. Final Touch
At last, we need to retouch our CSS for the final animation. Here our middle line moves to the left and other two rotate to 45 deg on click.
.menu-btn.open .menu-btn__burger {
transform: translateX(-50px);
background: transparent;
box-shadow: none;
}
.menu-btn.open .menu-btn__burger::before {
transform: rotate(45deg) translate(35px, -35px);
}
.menu-btn.open .menu-btn__burger::after {
transform: rotate(-45deg) translate(35px, 35px);
}
Here is the final preview-
Hope it helps!!!
Top comments (2)
👍❤️
I love it! Great job!