This content originally appeared on DEV Community and was authored by Swastik Yadav
In this post we will explore how we can create a toggle functionality for Menu / SideBar with pure CSS and no JavaScript.
Toggle functionality is often built with JavaScript because it requires handling the click event.
But it can be built with pure CSS and no JavaScript.
Here is how.
1 - The Markup
Let's start with a simple tag for the sidebar.
HTML
<aside class="aside-wrapper">
<h1 class="logo-text"><span>Qpay</span>
<i class="fas fa-bars sidebar-toggle"></i>
</h1>
<ul>
<li><i class="fas fa-home"></i> Home</li>
<li><i class="fas fa-building"></i> Company</li>
<li><i class="fas fa-dollar-sign"></i> Perks</li>
<li><i class="fas fa-file-contract"></i> Legal</li>
<li><i class="fas fa-credit-card"></i> Payments</li>
</ul>
<ul>
<li><i class="fas fa-headset"></i> Get Help</li>
<li><i class="fas fa-comment"></i> Chat With Us</li>
</ul>
</aside>
2 - Add input type checkbox
Just above the aside tag add an input type checkbox.
HTML
<input type="checkbox" id="toggler" checked />
<aside class="aside-wrapper">
<h1 class="logo-text"><span>Qpay</span>
<i class="fas fa-bars sidebar-toggle"></i>
</h1>
...
</aside>
3 - Toggle Sidebar
Now based on the checked / Unchecked state of the input, we can show and hide the sidebar in CSS.
The below code snippet says: If the input is checked, move the sidebar to the left by 250px. (250px is the width of the sidebar.)
CSS
/* Toggler Functionality */
input:checked ~ aside {
left: -250px;
}
Now toggling the checkbox will show and hide the sidebar.
4 - Hamburger Menu
But we want this to work when we click on the hamburger, not on the checkbox.
- Hide the input. (display: none)
- Wrap the hamburger menu in a label tag with the "for" attribute.
Id
of input checkbox and for
attribute for the label should be the same. (This will trigger the checkbox when we click on hamburger icon.)
HTML
<!-- Input checkbox "ID" = "toggler" -->
<input type="checkbox" id="toggler" checked />
<aside class="aside-wrapper">
<h1 class="logo-text"><span>Qpay</span>
<!-- Label "FOR" = "toggler" -->
<label for="toggler">
<i class="fas fa-bars sidebar-toggle"></i>
</label>
</h1>
...
</aside>
And that's it. We created a toggle functionality without JavaScript.
Here is a complete live demo with the codebase: https://codepen.io/swastikyadav/pen/zYZPyrN
If you enjoyed this post, found it useful, or felt happy please consider subscribing to my Weekly NewsLetter: https://swastikyadav.com/subscribe
Thank You!
This content originally appeared on DEV Community and was authored by Swastik Yadav
Swastik Yadav | Sciencx (2021-05-31T12:11:39+00:00) Menu / Sidebar toggle functionality with pure CSS and no JavaScript.. Retrieved from https://www.scien.cx/2021/05/31/menu-sidebar-toggle-functionality-with-pure-css-and-no-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.