Introduction#

create a simple sidebar using, demo here and using tailwind here

  • flex-box, flex-grow, flex-shrink, flex-basic
  • position fixed
  • desktop and mobile sidebar
web-css-color
<body>
<div class="container">
<aside class="sidebar" id="sidebar">
<ul class="sidebar-list">
<li class="sidebar-list__a">
<a href="#"> Product </a>
</li>
<li class="sidebar-list__a">
<a href="#"> Features </a>
</li>
<li class="sidebar-list__a">
<a href="#"> Pricing </a>
</li>
<li class="sidebar-list__a">
<a href="#"> Order </a>
</li>
</ul>
</aside>
<aside class="mobile-sidebar" id="mobile-sidebar">
<button id="hide-button">Hide</button>
<ul class="sidebar-list">
<li class="sidebar-list__a">
<a href="#"> Product </a>
</li>
<li class="sidebar-list__a">
<a href="#"> Features </a>
</li>
<li class="sidebar-list__a">
<a href="#"> Pricing </a>
</li>
<li class="sidebar-list__a">
<a href="#"> Order </a>
</li>
</ul>
</aside>
<div class="main">
<button id="show-button" class="toggle-button">Togge</button>
<h1>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Non porro
</h1>
</div>
</div>
</body>

Mobile Sidebar#

only display it when the toggle button is clicked, it position is fixed and width 100.

background-color: lightcyan;
height: 100vh;
overflow-y: auto;
position: fixed;
width: 100%;
display: none;
}

the toggle or menu button

window.onload = () => {
var hide = document.getElementById('hide-button')
var show = document.getElementById('show-button')
var sidebar = document.getElementById('mobile-sidebar')
hide.addEventListener('click', () => {
sidebar.style.display = 'none'
})
show.addEventListener('click', () => {
sidebar.style.display = 'block'
})
}

Desktop Sidebar#

then sidebar and main content are inside a flex-box container.

  • sidebar flex: 0 0 10rem, so it is not shrinkble, and initial width 10rem
  • main flex: 1 1 auto, so its width is max-content, then shrink, grow to take all avaiable space
.container {
display: flex;
max-width: 1080px;
margin: auto;
background-color: antiquewhite;
height: 100vh;
}
.sidebar {
background-color: lightcyan;
height: 100vh;
overflow-y: auto;
flex: 0 0 10rem;
display: block;
width: 10rem;
}
.main {
margin-left: 1rem;
margin-right: 1rem;
background-color: lightgray;
text-align: center;
overflow-y: auto;
flex: 1 1 auto;
}

Tailwind#

there are different ways to hide the sidebar when viewport is small

  • hidden sm:block
  • invisible sm:visible
  • transition-transform -translate-x-ful sm:translate-x-0
<aside class="fixed top-0 left-0 h-screen w-64 hidden sm:block">
<div>
<ul>
<li>
<a>
<svg></svg>
</a>
</li>
</ul>
</div>
</aside>

the main content shifted right by using margin left

<div class="bg-slate-200 p-4 sm:ml-64 overflow-y-auto h-screen">
<div class="p-4 bordeer-2 border-gray-200 border-dashed rounded-lg">
<div class="grid grid-cols-3 gap-4 mb-4">
<div class="flex items-center justify-center h-24 rounded bg-gray-40">
<p class="text-2xl text-gray-400">+</p>
</div>
</div>
</div>
</div>