In this article, we will know how to make a responsive sidebar or navbar with HTML and CSS for this you will need three things
use case
- Header
- nav
- ul
- hamburger button for mobile
- add active class to toggle sidebar to open & close
source code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
font-family: sans-serif;
}
header {
padding: 1rem;
background: #000;
display: flex;
color: #fff;
justify-content: space-between;
align-items: center;
position: sticky;
top: 0;
}
header .brand {
text-decoration: none;
font-size: 20px;
}
header button {
width: 40px;
outline: none;
border: none;
padding: 10px;
background: transparent;
color: #fff;
display: none;
cursor: pointer;
}
header button span {
display: block;
height: 2px;
margin-bottom: 3px;
background: #fff;
width: 100%;
}
header a {
color: #fff;
}
nav ul li {
padding: 5px 10px;
}
nav ul {
display: flex;
list-style: none;
}
@media (max-width:767px) {
header button {
display: inline-block;
}
header nav {
position: absolute;
top: 100%;
left: -100%;
background: #000;
width: 70%;
transition: all 0.3s;
opacity: 0;
}
header::after {
content: "";
width: 100%;
position: absolute;
top: 100%;
left: 0;
height: 100vh;
z-index: -1;
background: rgba(0, 0, 0, 0.7);
opacity: 0;
transition: all 0.3s;
}
header.active nav {
left: 0;
opacity: 1;
}
header.active::after {
opacity: 1;
}
header nav ul {
flex-direction: column;
height: 100vh;
}
nav ul li {
padding: 14px 10px;
border-bottom: 1px solid #f1f1f157;
display: block;
}
}
</style>
</head>
<body>
<header>
<a class="brand" href="">Website</a>
<button role="button">
<span></span>
<span></span>
<span></span>
</button>
<nav>
<ul>
<li>Home</li>
<li>Home</li>
<li>Home</li>
<li>Home</li>
<li>Home</li>
</ul>
</nav>
</header>
<script>
document.querySelector("header button").onclick = () => {
document.querySelector("header").classList.toggle("active")
}
</script>
</body>
</html>