responsywne menu hamburger js css

Podstawowe menu responsywne typu hamburger

Jak stworzyć podstawowe menu, które na małym ekranie przekształci się w przycisk typu hamburger?

W pliku html dodajemy kod menu wraz z funkcją JavaScript. W tym przykładzie menu zbudowane jest ze zwykłych linków.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Responsywne menu</title>
        <script src="https://kit.fontawesome.com/359f743a12.js" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="style.css" type="text/css">
    </head>
    <body>
        <div class="topnav" id="myTopnav">
            <a href="index.html">Home</a>
            <a href="index.html">News</a>
            <a href="index.html">Contact</a>
            <a href="index.html">About</a>
            <a href="javascript:void(0);" class="icon" onclick="myFunction()">
              <i class="fa fa-bars"></i>
            </a>
        </div>
        <script>
            function myFunction() {
              var x = document.getElementById("myTopnav");
              if (x.className === "topnav") {
                x.className += " responsive";
              } else {
                x.className = "topnav";
              }
            }
        </script>
    </body>
</html>

W pliku style.css dodajemy następujący kod:

.topnav {
    overflow: hidden;
    text-align: center;
  }
  
.topnav a {
    display: inline-block;
    color: #505050;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 18px;
}
  
.topnav a:hover {
    background-color:#505050;
    color: #ebebeb;
}

.topnav .icon {
    display: none;
}

@media screen and (max-width: 768px){
    .topnav{
        text-align: left;
    }
    .topnav a:not(:first-child) {display: none;}
    .topnav a.icon {
      float: right;
      display: block;
    }
    .topnav.responsive {position: relative;}
    .topnav.responsive a.icon {
      position: absolute;
      right: 0;
      top: 0;
    }
    .topnav.responsive a {
      float: none;
      display: block;
      text-align: left;
    }
}
Scroll to Top