How to create a collapsible sidebar menu with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

Following is the code to create a collapsible sidebar menu 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" />
.sideNav {
   height: 100vh;
   width: 0;
   position: fixed;
   z-index: 1;
   top: 0;
   left: 0;
   background-color: rgb(46, 218, 195);
   overflow-x: hidden;
   padding-top: 60px;
   transition: 0.5s;
.sideNav a {
   padding: 8px 8px 8px 32px;
   text-decoration: none;
   font-size: 25px;
   color: #000000;
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   display: block;
   transition: 0.3s;
.sidenav a:hover {
   color: #f1f1f1;
.sideNav .closeBtn {
   position: absolute;
   top: 0;
   right: 25px;
   font-size: 36px;
   margin-left: 50px;
button {
   padding: 15px;
   background-color: rgb(0, 27, 145);
   color: rgb(255, 255, 255);
   font-size: 20px;
   border: none;
   border-radius: 2%;
   transition: 0.5s;
<nav class="sideNav">
<a href="#" class="closeBtn">×</a>
<a href="#">Login</a>
<a href="#">Register</a>
<a href="#">Home</a>
<a href="#">About Us</a>
<main class="main-content">
<button class="openSideNav">Click here to open sideNav</button>
<h1>Here is some sample text</h1>
<p>Here is some random sample text too</p>
let openBtn = document.querySelector(".openSideNav");
openBtn.addEventListener("click", () => {
let closeBtn = document.querySelector(".closeBtn");
closeBtn.addEventListener("click", () => {
function showNav() {
   document.querySelector(".sideNav").style.width = "300px";
   document.querySelector('.main-content').style.marginLeft = "300px";
function hideNav() {
   document.querySelector(".sideNav").style.width = "0";
   document.querySelector('.main-content').style.marginLeft = "0px";


The above code will produce the following output −

On clicking the open sideNav button the navigation menu will slide from left as follows −

Updated on 06-Apr-2020 11:26:33