Navigation Bar
How to make a accessibility-friendly responsive navigation bar using HTML, CSS and JavaScript.
Building a Responsive Navigation Bar
A responsive navigation bar is essential for the majority of sites.
Below is a working example of the navigation bar. On large screen it shows all navigation links directly, on smaller screens it hides them behind a hamburger menu.
So how can you build this?
The HTML, CSS and JavaScript
HTML
The HTML for a navigation bar that contains a logo and a group of navigation links. The button with the aria-controls
is used to toggle the hamburger navigation view on the mobile screen. The hamburger and close icon are not shown on the desktop screen. In the mobile view only one of them is shown, depending on the toggle state, more on that in the CSS section.
The visually hidden span containing Menu
is used for people with screen readers.
CSS
The CSS to style the navbar. The styling for the desktop view is straightforward, hiding the menu-toggle-button
and showing the navigation list in a flex group horizontally.
The navigation for the mobile view is more complex. This is a good example of where the “mobile first” design approach would be a hindrance. It’s better to start with least complex first, which usually is the mobile view, but not always like in this case.
The navigation gets hidden, when aria-navigation
is set to true
the styles are applied and the navigation is shown in the hamburger view. This toggle also changes which icon we want to display.
Content that would be in other css files like reset.css & utility.css
This CSS code is included in the Codepen example but you would not put this part into the component itself, instead you want to define these in other CSS files, more in these in CSS Reset and CSS Utility Classes.
JavaScript
The JavaScript allows us to toggle the hamburger menu.
When we click the hamburger icon it opens up. When we click a link, the closing icon or the area outside of the navigation it closes again.
It is also possible to build a navigation bar without JavaScript, but since these can’t control the aria labels their accessability is worse.
Sources & References
- Building a responsive Navbar by Kevin Powell: https://youtu.be/HbBMp6yUXO0
- Building header for Astro blog page by Kevin Powell (timestamped) https://youtu.be/Thudicbgqtg?list=LL&t=1941