Responsive sidebar using CSS
People tend to use the phone more surfing the web nowadays. As the screens often are so small, a sidebar is not the best idea. This is a quick on guide how you can use only CSS to make your sidebar to a bottom bar on phone screens.
1. Setup HTML
We need a basic HTML setup, something like this.
<body>
<nav class="sidenav">
<ul class="sidenav-nav">
<li class="sidenav-item">
<a class="sidenav-link">
<span class="las la-3x la-home icon"></span>
<span class="link-text">Dashboard</span>
</a>
</li>
<!-- MORE NAV LINKS -->
</ul>
</nav>
<main>
<!-- MAIN CONTENT GOES HERE -->
</main>
</body>
The first span
item within the nav is an icon, using the Line Awesome icons, in case you were wondering.
2. Position sidebar correctly
We will use CSS to position our sidebar to the left as standard.
main {
padding: 1rem;
margin-left: 10rem; /* SIDEBAR WIDTH */
height: 100vh;
}
.sidenav {
position: fixed;
width: 10rem; /* SIDEBAR WIDTH */
left: 0;
background-color: white;
height: 100vh;
}
.sidenav-nav {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
align-items: left;
height: 100%;
}
.sidenav-item {
width: 100%;
}
.sidenav-link {
display: flex;
align-items: center;
height: 4rem;
text-decoration: none;
}
.link-text {
margin-left: 0.5rem;
}
.icon {
margin: 0 0.5rem;
}
Ok, so there is a lot of styling going on here. The 2 first are the most important. They allow the sidebar to be fixed to the left side, moving the main container over the same width to the right.
The rest is basically styling to align the sidebar more nicely. Use the code if you want, or modify it the way you want to have it.
3. Make it responsive (a bottom bar) on smaller screens
We want to make it appear as a bottom bar on smaller screens, for this, we will use media queries.
/* Small screen */
@media only screen and (max-width: 600px) {
main {
height: calc(100vh - 5rem); /* BOTTOM BAR HEIGHT */
}
.sidenav {
bottom: 0;
width: 100vw;
height: 5rem; /* BOTTOM BAR HEIGHT */
align-items: flex-start;
padding-top: 0.4rem;
}
.sidenav-nav {
flex-direction: row;
margin-top: 0;
align-items: flex-start;
}
.sidenav-link {
justify-content: center;
}
.link-text {
display: none;
}
}
Once again, the two top ones are the most important. We use the same technique as previously, by moving up main
by 5rem
, which is the height of the bottom bar. The rest is styling to make it look good.