How to build a Responsive Navigation Bar with HTML, CSS and JavaScript.

Mary Maina
4 min readAug 19, 2020

Responsive design is useful when rendering a web page on different screen sizes.It helps to get rid of distortion or irregularities which may be present while displaying a web page.

This post describes how to build a responsive navigation bar using HTML,CSS and Vanilla JavaScript.

What do you need?

  • Basic knowledge about HTML, CSS and JavaScript
  • A text editor of your choice.

The structure of the HTML Code

.The tag that contains the navbar is the header tag.

Inside the ‘nav’ tag there are three elements: a div with a class of ‘logo’ , a Ul(unordered list) with a class of ‘nav-links’ and a div with a class of ‘burger’.

The div with a class of ‘burger’ has three empty divs which will be styled to form the hamburger icon.

The ul contains list tags(li), each with an embedded link. The list tags would be styled to be the navigation links.

The <script> tag is used to embed a client-side script (JavaScript).

CSS Code

We use flexbox layout model to horizontally arrange the elements in the navigation

The ‘burger’ class display value is set to none. This ensures the hamburger icon does not show on desktop view.

Mobile responsiveness media Query

When a media query matches the specified media type , the corresponding style sheet or style rules are applied, following the normal cascading rules.

The flex-direction: column The column value stacks the flex items vertically (from top to bottom):

The translateX() CSS function re-positions an element horizontally on the 2D plane. Its result is a <transform-function> data type.

By default when our navigation is in mobile mode, the ul is closed and the hamburger icon is displayed as shown below:

closed navigation

To make sure the active class and toggle class works, we add the following block of CSS code after the media query.

The transformation function rotates the div with a class of bar1 and class of bar2 to a different icon when the hamburger icon is toggled.

Adding the Menu Toggle functionality

In the markup, the div tag surrounding the three empty divs has a class of ‘burger’.

We add a click event to that class :what happens is every time we click on the hamburger icon? A class of .active is added to our ul tag and a class of .toggle is added to the ‘burger’ class.

If we look back at the markup, the ul tag has a class of ‘nav-links’ and the div tag has a class of ‘burger’

When the active class is added, the hamburger icon opens the navigation.

When we click on the hamburger again, the active class is removed and the menu collapses.

--

--

Mary Maina

Software Developer. Passion is the fire that Lights your way.