With Bootstrap 4, I successfully implemented a functionality where clicking a button hides/shows the sidebar on desktop, allowing the main content area to occupy the remaining space:
HTML:
<a class="sidebar-toggle" href="#"><i class="fa fa-bars"></i></a>
<div class="d-flex wrapper">
<div class="sidebar sidebar-dark bg-dark">
<ul class="list-unstyled">
<li><a href="#"><i class="fa fa-fw fa-link"></i> Menu Item</a></li>
<li><a href="#"><i class="fa fa-fw fa-link"></i> Menu Item</a></li>
<li><a href="#"><i class="fa fa-fw fa-link"></i> Menu Item</a></li>
</ul>
</div>
<div class="content m-4">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</div>
CSS:
.sidebar {
min-width: 220px;
max-width: 220px;
min-height: calc(100vh - 56px);
}
.wrapper-toggled .sidebar {
margin-left: -220px;
}
JS:
$(document).on('click', '.sidebar-toggle', function (event) {
event.preventDefault();
$('.wrapper').toggleClass('wrapper-toggled');
});
However, I encountered issues with displaying the sidebar on mobile devices. When shown, it causes a horizontal scrollbar and affects the viewport height.
Here is my code for addressing the mobile behavior:
@media (max-width: 768px) {
.sidebar {
margin-left: -220px;
}
.wrapper-toggled {
transform: translate(220px, 0);
}
}
I attempted fixing this by using overflow-x: hidden
, but it didn't work as expected. Additionally, displaying the sidebar seems to alter the total viewport height on mobile devices.
Is there a better approach to handle this issue? How can I resolve these problems?