In this tutorial we are going to create a sidebar using HTML, CSS and JavaScript. We will begin with a basic layout. A left sidebar hosts a menu and its content section. When the user presses the button, the left sidebar will be visible with an smooth animation effect which we have added with the CSS transition in sidebar.
<!DOCTYPE html>
<html>
<head>
<title>CSS Transition Sidebar with HTML - Coding Is Easy</title>
<style>
*, html {
margin: 0;
padding: 0;
}
.main {
font-family: Arial, Verdana, sans-serif;
}
.sidebar {
background-color: #264653;
width: 12rem;
height: 100vh;
padding: 0;
position: fixed;
transition: transform 300ms ease-in;
}
.sidebar--isHidden {
transform: translateX(-12rem);
transition: transform 300ms ease-out;
}
.sidebar-menu {
list-style: none;
padding: 1.5rem;
margin-top: 0;
}
.sidebar-menu__item {
display: block;
cursor: pointer;
margin-bottom: 0.5rem;
}
.sidebar-menu__item a {
color: #e9c46a;
text-decoration: none;
display: block;
}
.sidebar-menu__item a:hover {
color: #e76f51;
transition: color 150ms linear;
}
.content {
background-color: #5a5a5a;
padding: 2rem;
height: 100vh;
color: white;
}
#toggle {
background-color: #e9c46a;
border: 2px solid #f4a261;
padding: 0.5rem 2rem;
cursor: pointer;
transition: all 150ms linear;
margin-top: 20px;
}
#toggle:hover {
background-color: #f4a261;
transition: all 150ms ease-in;
}
</style>
</head>
<body>
<div class="main">
<div class="sidebar sidebar--isHidden">
<ul class="sidebar-menu">
<li class="sidebar-menu__item"><a href="#">Home</a></li>
<li class="sidebar-menu__item"><a href="#">News</a></li>
<li class="sidebar-menu__item"><a href="#">Contact</a></li>
<li class="sidebar-menu__item"><a href="#">About</a></li>
</ul>
</div>
<div class="content">
<div style="text-align: center; margin-top: 2rem">
<div>Animated - CSS Transition Sidebar by CodingIsEasy.com</div>
<button id="toggle">Show Sidebar</button>
</div>
</div>
</div>
<script>
window.addEventListener("DOMContentLoaded", () => {
document.getElementById("toggle").addEventListener("click", () => {
const sidebarEl = document.getElementsByClassName("sidebar")[0];
sidebarEl.classList.toggle("sidebar--isHidden");
document.getElementById("toggle").innerHTML = sidebarEl.classList.contains(
"sidebar--isHidden"
)
? "Show Sidebar"
: "Hide Sidebar";
});
});
</script>
</body>
</html>

And when we click on Show sidebar, we get to see something like this and the sidebar opens with the animation effect:
