How To Create a Menu Icon
Click on the Menu Icon to transform it to "X":
A menu icon, also known as a hamburger icon, is a common design element that allows users to access a navigation menu on mobile devices. In this blog post, we will show you how to create a menu icon using HTML, CSS and JavaScript.
First, create a container with three bars representing the icon's lines. The container has an onclick event triggering a function to toggle a class for the transformation.
<div class="container" onclick="toggleMenuIcon(this)">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
Next, we need to write some CSS code to style the menu icon. We will use the display, width, height, margin, background-color and position properties to adjust the appearance and position of the div and span elements. We will also use the transform and transition properties to create some animation effects when the menu icon is clicked.
.container {
display: inline-block;
cursor: pointer;
}
.bar1, .bar2, .bar3 {
width: 35px;
height: 5px;
background-color: #333;
margin: 6px 0;
transition: 0.4s;
}
.change .bar1 {
transform: translate(0, 11px) rotate(-45deg);
}
.change .bar2 {
opacity: 0;
}
.change .bar3 {
transform: translate(0, -11px) rotate(45deg);
}
Finally, we need to write some JavaScript code to add some functionality to the menu icon.
function toggleMenuIcon(x) {
x.classList.toggle("change");
}
That's it! You have successfully created a menu icon using HTML, CSS and JavaScript. You can now use it to enhance your mobile web design and improve your user experience.