Coders' Guidebook

How to make your website's navigation bar responsive (mobile-friendly)

When you build a website, it is important to check it looks good and works correctly on both computers and mobile devices. One key consideration is the different screen sizes of these devices; content that looks good on a computer may not display correctly on smaller screen sizes and mobile devices. A website that adapts to different screen sizes is said to be "responsive". In this tutorial, we will explore how to make your website's navigation bar responsive using HTML, CSS and JavaScript.

responsive-navigation-bar-css-javascript.png

HTML code

In our tutorial on how to build a navigation bar, we began the code for the navigation bar with an opening 'div' tag which was assigned the class 'navbar'. To complete this tutorial, you will also need to assign that div tag an id of 'myTopnav' as follows:

<div class="navbar" id="myTopnav">

An id is similar to a class in that it allows an element to be styled using CSS or made interactive using JavaScript; however, unlike classes, id's are only meant to be used by one specific element. The id we have applied here will be used later when we make the navigation bar collapsable/expandable on small screens.

To make the navigation bar functional on small screens, we must add an icon that allows visitors to collapse and expand the contents of the navigation bar. The bars icon we will use is shown below.

fa-bars.png

To use the bars icon on your website, you will need to import the font awesome stylesheet: an external stylesheet which gives your website access to over a thousand icons. To incorporate the stylesheet, add the following code to the head element of your HTML file:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Next, to add the bars icon to the web page, insert the following code after the links in your navigation bar:

<a href="javascript:void(0);" class="icon" onclick="expansion()">
	<i class="fa fa-bars"></i>
</a>

In the above code, the expansion() onclick function is a reference to some JavaScript we will add later. Meanwhile, the i (icon) tags with the 'fa fa-bars' class load the bars icon from the font awesome stylesheet.

Altogether, the complete entry for the navigation bar in the HTML file should look like this:

<div class="navbar" id="myTopnav">
	<a href="http://treesandtrees.com">Home</a>
	<a href="http://treesandtrees.com/About/">About</a>
	<a href="http://treesandtrees.com/TreeTypes/">Types of Trees</a>
	<a href="javascript:void(0);" class="icon" onclick="expansion()">
		<i class="fa fa-bars"></i>
	</a>
</div>

CSS code

We'll now turn our attention to how the navigation bar should be styled. Open the 'main.css' stylesheet and add the following entry:

.navbar .icon {
	display: none;
}

The above code sets the display property for the bars icon to 'none', which means they will be hidden by default. To reveal the bars icon on small screens, add the following CSS code:

@media screen and (max-width: 650px) {
	.navbar a:not(:first-child) {display: none;}
	.navbar a.icon {
		display: block;
		float: right;
	}
}

The @media screen and (max-width: 650px) declaration instructs the web browser to only apply the forthcoming styling information if the screen size is less than 650px wide (e.g. mobile phones). Adding :not(:first-child) after .navbar a is optional but will ensure the first link in the navigation bar (e.g. 'Home') is exempt from the display: none; property. This means the Home link will continue to be displayed even when all other links are hidden. Instructing .navbar a.icon to display as a block and float to the right unhides the bars icon on small screens and positions it on the right-hand side of the navigation bar.

The JavaScript code we are going to write shortly will add a class called 'expanded' to the 'navbar' class when the bars icon is clicked. The following CSS code determines the style of the navigation bar when expanded:

@media screen and (max-width: 650px) {
	.navbar.expanded a.icon {
		position: absolute;
		right: 0;
		top: 0;
	}
	.navbar.expanded a {
		float: none;
		display: block;
		text-align: left;
	}
}

In the above code, the .topnav.expanded a.icon entry fixes the bars icon in the top right-hand corner of the navigation bar. Meanwhile, .navbar.expanded a determines how the links will appear after the bars icon is clicked and the navigation bar expands. The 'block' display property unhides the links, while the 'none' float and 'left' text-align properties ensure the links organise themselves down the left-hand side of the expanded navigation bar.

If you followed our tutorial on how to build a navigation bar then you may have declared a 'height' CSS attribute for the .navbar class. While a fixed height value can prevent the navigation bar from obscuring other parts of the webpage, it also stops the navigation bar from expanding when the bars icon is clicked. To override this, you should make an entry for .navbar.expanded and set its height attribute to 'auto'. Doing this ensures the navigation bar can expand as far as it needs to when the bars icon is clicked.

.navbar.expanded {
	height: auto;
}

JavaScript code

The final step is to add some JavaScript to the HTML file. We could copy and paste the JavaScript code into the head element of each web page that uses the navigation bar; however, this is suboptimal. If we are going to use the same JavaScript on multiple webpages then it makes more sense to link all web pages with the navigation bar to a single JavaScript file (similar to how we link multiple webpages to the same CSS stylesheet).

Create a new JavaScript file in your code editor and save it in the same folder as your homepage (index.html). Use the filename 'navbar' and JavaScript file (.js) extension, so the full file should be called navbar.js. Once that is done, add the following code to the navbar.js file:

function expansion() {
  var x = document.getElementById("myTopnav");
  if (x.className === "navbar") {
    x.className += " expanded";
  } else {
    x.className = "navbar";
  }
}

The above code will add the 'expanded' class to the 'navbar' class when the bars icon is clicked. It allows the navigation bar to expand and reveal its navigation links. If the bars icon is clicked again then the 'expanded' class is removed and the links are hidden once more.

Next, return to your HTML web page and add the following statement to the head element to import the navbar.js file:

<script src="navbar.js"></script>

If the HTML web page is in a subfolder relative to the navbar.js file, then you will need to add '../' before 'navbar.js'. '../' tells the browser the 'navbar.js' file is located in a parent folder.

Altogether, the overall HTML file should look like this:

<!DOCTYPE html>
<html lang="en-GB">
<head>
	<title>Home</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" type="text/css" href="main.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
	<script src="navbar.js"></script>
</head>
<body>
	<div class="navbar" id="myTopnav">
		<a href="http://treesandtrees.com">Home</a>
		<a href="http://treesandtrees.com/About/">About</a>
		<a href="http://treesandtrees.com/TreeTypes/">Types of Trees</a>
		<a href="javascript:void(0);" class="icon" onclick="expansion()">
			<i class="fa fa-bars"></i>
		</a>
	</div>
</body>
</html>

<<< Previous

Next >>>