How to create a responsive offcanvas navigation menu

Nowadays every modern website has some sort of responsive navigation menu. A menu that’s adapted for touch devices such as tablets and smartphones. In this blog post I’ll show you how to create a simple offcanvas navigation menu as it can provide an extremely useful and beautiful experience for your users. Let’s go!

Introduction

Before we start you should take a look at what we’re trying to achieve here. This is a live demo of our project on codepen. Click on “Open offcanvas menu” to see offcanvas in action.

See the Pen Simple HTML, LESS, jQuery responsive offcanvas navigation menu by Alen (@alenvuletic) on CodePen.

We’ll use CSS3 transitions and translations to achieve opening and closing animation.

The whole CSS is written in LESS language, and if you want to see a compiled version just click on “View compiled” button in codepen CSS section.

Also there are useful comments in CSS file which tells you which code is important to include if you want your offcanvas to work properly.

The HTML

We’ll start with HTML. There are 2 important divs we’ll use in this tutorial.

offcanvas

The first one is “.page-wrap”. In this div you insert your default website content. In this case we’ll put in content from our codepen demo.

The second one is “.offcanvas”. Here you put in content that will be shown in offcanvas when it’s opened. In this case we have a simple unordered list.

The JavaScript

After HTML we’ll setup some JavaScript code to make everything work.

We’re going to create toggle that will add / remove “.offcanvas-expanded” class to the body when we click on the button with “.offcanvas-toggle” class.

The CSS

In this article I’ll include only the important CSS code that’s necessary for offcanvas to work properly.

Firstly we’ll add this line of code to prevent horizontal scroll on the body when offcanvas is activated.

Now we’ll setup “.page-wrap”. Page wrap is an element that we have to move to the right when we have “.offcanvas-expanded” class active on the body and we’ll do that with the CSS “transform”. To create a smooth slide effect we’ll add the CSS “transition” on the “.page-wrap”.

It’s time to style “.offcanvas”. We’ll do the same thing as with “.page-wrap” to reveal “.offcanvas” div when “.offcanvas-expanded” class is active on the body.

Conclusion

Boom! You’re now ready to go to create your offcanvas navigation menu. Now you can play around with it and make it even better. Hope you’ve learned something from this article . I’d love to hear what you think.

About Alen Vuletic

Front-end developer from Split, Croatia. I love sports, nature and apple devices.