How to Create a Responsive Side Navigation Menu with CSS

Having a responsive website has become a must.

A responsive website adjusts itself according to the screen size of the device it’s being viewed on.

A responsive side navigation menu is a key component of a responsive website.

In this tutorial, we’ll go through the process of creating a responsive side navigation menu using CSS.


HTML Structure

First, we need to set up the HTML structure of our menu.

We’ll create an unordered list to hold our menu items. Each menu item will be a list item within the unordered list.

Here’s the HTML code:

<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>

CSS Styles

Next, we’ll style our menu using CSS. To make our menu responsive, we’ll use media queries.

Media queries allow us to apply different styles based on the screen size of the device.

We’ll use two breakpoints in this example: one for screens larger than 720px and another for screens smaller than 720px.

For screens larger than 720px:

nav {
display: flex;
justify-content: center;
align-items: center;
height: 60px;
background-color: #333;
}
nav ul {
display: flex;
}
nav ul li {
list-style: none;
margin: 0 20px;
}
nav ul li a {
color: #fff;
text-decoration: none;
font-size: 20px;
}

For screens smaller than 720px:

@media screen and (max-width: 720px) {
nav {
height: auto;
}
nav ul {
flex-direction: column;
width: 100%;
}
nav ul li {
margin: 20px 0;
text-align: center;
}
nav ul li a {
font-size: 18px;
}
}

JavaScript Code

Finally, we’ll add some JavaScript to toggle the menu for small screens.

The JavaScript code will toggle a class called active on the menu when the menu icon is clicked.

The active class will have styles applied to show and hide the menu.

const menuIcon = document.querySelector('.menu-icon');
const nav = document.querySelector('nav');

menuIcon.addEventListener('click', () => {
  nav.classList.toggle('active');
});

Conclusion

In this tutorial, we’ve gone through the process of creating a responsive side navigation menu using CSS.

We started with the HTML structure, followed by the CSS styles, and finished with some JavaScript to toggle the menu for small screens.

With these steps, you’ll be able to create a responsive side navigation menu for your website.