How to Create: Menu Icon

Learn how to create menu icons using CSS.

If you don't use an icon library, you can use CSS to create a basic menu icon:

Menu Icon:

Try it yourself

Animated Menu Icon (Click on it):

Try it yourself

How to Create Menu Icons

First step - Add HTML:

<div></div>
<div></div>
<div></div>

Second step - Add CSS:

div {
  width: 35px;
  height: 5px;
  background-color: black;
  margin: 6px 0;
}

Try it yourself

Example Explanation:

width and height Properties specify the width and height of each bar.

We added a black background color and top and bottom margins to create space between each bar.

Animation icon

Use CSS and JavaScript to change the menu icon to a 'cancel/delete' icon when clicked:

First step - Add HTML:

<div class="container" onclick="myFunction(this)">
  <div class="bar1"></div>
  <div class="bar2"></div>
  <div class="bar3"></div>
</div>

Second step - Add CSS:

.container {
  display: inline-block;
  cursor: pointer;
}
.bar1, .bar2, .bar3 {
  width: 35px;
  height: 5px;
  background-color: #333;
  margin: 6px 0;
  transition: 0.4s;
}
/* Rotate the first bar */
.change .bar1 {
  transform: translate(0, 11px) rotate(-45deg);
}
/* Fade out the second bar */
.change .bar2 {opacity: 0;}
/* Rotate the last bar */
.change .bar3 {
  transform: translate(0, -11px) rotate(45deg);
}

Third step - Add JavaScript:

function myFunction(x) {
  x.classList.toggle("change");
}

Try it yourself

Example Explanation:

HTML and CSS: We use the same styles as before, but this time we wrap each <div> element with a container element and specify a class name for each element.

Container elements are used to display a pointer symbol when the user hovers over the divs (lines). When clicked, it will execute a JavaScript function that adds a new class name to it, which will change the style of each horizontal bar: the first and last lines will deform and rotate into the letter 'x'. The middle lines will fade out and become invisible.