In this article, we will be creating a navigation bar that is completely responsive on desktop as well as on mobile devices.

Before starting let’s see the folder structure,

CSS

| — — styles.css

index.html

app.js

So now let’s get started,

First, let’s create a layout for our navigation bar,

So let’s first create an index.html file and start writing HTML code. In this, I will be using the font awesome icon for the hamburger menu and we have to add its link to include the icon in the script tag.

In this, I have also added some classes to tags so that we can add CSS to that element or tag later.

With the above code, our page will look like as shown below,

The layout of our HTML page

Now, let’s add CSS to our amazing navigation bar!

To add CSS we first have to include the stylesheet in our HTML file so that it will reflect on our website.

To do that we will just include the following line in the head tag,

Now in the styles.css file, we will finally be styling our navigation bar

After styling our website will be looking as shown below,

Navigation bar after adding CSS

Here, we can see that toggle icon in the navigation bar which should not be visible on bigger screens. To hide the icon we can use the display property to the navbar_toggle class and set it to none as shown below,

.navbar_toggle {

display: none;

}

Now we have to make it responsive on mobile devices. To do that we will be using media queries. So what are media queries?

It is a technique used in CSS to add CSS properties only if certain conditions are true.

Adding Media Queries

Here we will be adding media queries in,

@media only screen and (max-width : 992px){

}

This means the CSS property mentioned inside the media block will be applied only if the browser window is 992px or smaller.

In this, we hiding the main_nav class and added show_nav class which we will use to toggle the button to show the navigation menu using javascript.

In show_nav we will be making flex-direction to the column so that the menu items will be stacked one upon another.

So after adding media queries our navigation bar will be looking as shown below,

Now our work is almost done, we only have to add javascript to display the navigation menu.

First, let’s create an app.js file and add it to the script tag in the index.html file as shown below,

Now in the app.js, write the following code, here we select the navbar_toggle and main_nav class and add the event listener to it so that it will toggle when the toggle icon is being clicked.

If we clicked the toggle icon our page will be as shown below,

Navigation Bar in Mobile Devices

So this is how we can create a responsive navigation bar by adding media queries and little Javascript.

#css-flexbox #navigation-bar #javascript #html #js #css

Create a Responsive Navigation Bar in HTML, CSS, and JS!
2.55 GEEK