How to make a hamburger button in HTML and CSS

How to make a hamburger button in HTML and CSS

In this article, we’ll look at a very simple example of implementing an animated hamburger button.

You’ve probably seen similar buttons on websites with mobile layouts. Such a button can also be found in Bootstrap versions 3 and 4.

To implement this button, we’ll need:

  1. HTML
  2. CSS3 (in our case, we’ll use SCSS)
  3. JavaScript (specifically jQuery)

Here’s what our button looks like in HTML:

<div class="hamburger">
  <span class="hamburger-line"></span>
  <span class="hamburger-line"></span>
  <span class="hamburger-line"></span>
</div>

Nothing complicated here:
A `DIV` with the class “hamburger” is the button itself, with predefined dimensions.
Each `SPAN` with the class “hamburger-line” represents one of the lines of the button.

Next comes the SCSS code:

.hamburger {
  width: 30px;
  margin: 0 auto;
  
  &-line {
    width: 100%;
    height: 4px;
    background-color: #158100;
    display: block;
   
    -webkit-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
    
    &:nth-child(2){
       margin: 6px auto;
    }
  }
  
  &:hover{
    cursor: pointer;
  }

  &.hamburger-active .hamburger-line:nth-child(2){
    opacity: 0;
  }

  &.hamburger-active .hamburger-line:nth-child(1){
    -webkit-transform: translateY(10px) rotate(40deg);
    -ms-transform: translateY(10px) rotate(40deg);
    -o-transform: translateY(10px) rotate(40deg);
    transform: translateY(10px) rotate(40deg);
  }

  &.hamburger-active .hamburger-line:nth-child(3){
    -webkit-transform: translateY(-10px) rotate(-40deg);
    -ms-transform: translateY(-10px) rotate(-40deg);
    -o-transform: translateY(-10px) rotate(-40deg);
    transform: translateY(-10px) rotate(-40deg);
  }
}

For those familiar with CSS, the code above shouldn't cause any issues. But for beginners, here’s a short explanation:

  1. The transition property enables animation
  2. The transform property allows element transformation
  3. :nth-child is a pseudo-class selector

And finally, the JavaScript code using jQuery:

$(document).ready(function(){
  $(".hamburger").click(function(){
    $(this).toggleClass("hamburger-active");
  });
});

Here, when the hamburger is clicked, we add or remove the “hamburger-active” class. This class is styled in CSS to animate the first and third lines with a 45-degree rotation, while the second line (the SPAN with the “hamburger-line” class) becomes hidden.

You can see the full implementation on this page.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *