Responsive Navigation Example

Go back to HTML and CSS Index

Today we will create a responsive navigation menu. In this example, we see how to create an open/close bars menu on a mobile device and change it to a "full" navigation in the desktop version.

The example requires a bit of JavaScript.

RWD: The navigation

We start by creating a navigation menu inside the body element in the HTML document:

HTML example

<header>
<nav class="firstnav">
<a href="#" class="logo">Logo</a>
<i class="navToggle">Menu</i>
</nav>
<nav class="mainnav">
<ul>
<li>
<a href="#">Menupunkt 1</a>
</li>
<li>
<a href="#">Menupunkt 2</a>
</li>
</ul>
</nav>
</header>
9.1 | The navigation

Next up, we add style instructions to the navigation menu, focusing on the desired starting point in the mobil version with only the logo and bars icon visible, the navigation menu collapsed.

The CSS

* {
margin: 0;
box-sizing: border-box;
}
header {
background-color: #333;
color: white;
}
a {
color: white;
}
.firstnav {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 20px;
}
.mainnav {
display: none;
}
9.2 | Styling the navigation menu (mobile layout)

We hide the main navigation by setting the display property value to none.

We then add media queries to our CSS making the navigation menu display right in the desktop version:

The CSS

@media screen and (min-width: 1024px) {
header {
display: flex;
}
.firstnav {
width: auto;
}
.mainnav {
display: flex;
width: 100%;
}
.mainnav ul {
list-style-type: none;
padding: 0;
display: flex;
align-items: center;
}
.navToggle {
display: none;
}
}
.toggleShow {
display: flex;
flex-direction: column;
}
9.3 | Styling the navigational menu (desktop version)

The .toggleShow class will be added to or removed from the element once clicked, depending on the actual state.

To "activate" the bars icon, making it open and close the navigational menu, we add a bit of JavaScript:

The HTML

<script>
const navbarToggle = () => {
const nav = document.querySelector('.mainnav');
nav.classList.toggle('toggleShow');
}
document.querySelector('.navToggle').addEventListener('click', navbarToggle);
</script>
9.4 | The JavaScript

The script element is placed in the bottom of the HTML document, just above the end body tag.

Now, when we click on "Menu", the navigational menu should show up.

The last bit missing is to style the .mainnav element, so that the navigation items are shown in the correct way, when the navigation menu is opened:

style.css

.mainnav li {
padding: 20px 20px;
width: 100%;
}
9.5 | Styling the list

The "Menu" text can now be replaced with the bars icon.

This was of course a simple example, and it may need some additional styling, but as long as you make sure the .navToggle class is placed correctly, and the .toggleShow class is styled correctly in the CSS, the example should work.