How to create a top navigation menu for smartphones / tablets with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

Following is the code to produce top navigation menu for smartphones and tablets screen size specially using CSS and Javascript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
body {
   margin: 0px;
   padding: 0px;
nav {
   position: relative;
   top: 0;
   width: 100%;
   background-color: rgb(39, 39, 39);
   overflow: auto;
   height: auto;
.links {
   display: inline-block;
   text-align: center;
   padding: 14px;
   color: rgb(178, 137, 253);
   text-decoration: none;
   font-size: 17px;
.links:hover {
   background-color: rgb(100, 100, 100);
.selected {
   background-color: rgb(0, 18, 43);
.hamburger {
   color: white;
   font-weight: bolder;
   display: none;
@media screen and (max-width: 600px) {
nav a:not(:first-child) {
   display: none;
nav a.hamburger {
   float: right;
   display: block;
   padding: 12px;
nav.openNav a.hamburger {
   position: absolute;
   right: 0;
   bottom: 0;
nav.openNav a {
   float: none;
   display: block;
   text-align: center;
<nav class="bottomNav">
<a class="links selected" href="#"> Home</a>
<a class="links" href="#"> Login</a>
<a class="links" href="#"> Register</a>
<a class="links" href="#"> Contact Us</a>
<a class="links" href="#">More Info</a>
<a class="hamburger">☰</a>
<p>Some random text here </p>
<p>Some random text here </p>
function toggleNav() {
   var x = document.getElementsByTagName("nav")[0];
   if (x.className === "bottomNav") {
      x.className += " openNav";
   } else {
      x.className = "bottomNav";
document.querySelector(".hamburger").addEventListener("click", toggleNav);


The above code will produce the following output −

On resizing the screen or on mobile screens the hamburger button will be shown as follows −

On clicking the hamburger button −

Published on 06-Apr-2020 14:49:50