Responsive Menu

No matter whether your navigation menu is across the top of the web page or down the side, it will not fit properly on narrow screens. To keep the menu available on those screens while not having it block access to the content we can have the page display a button when the viewport is too narrow for both the menu and the content to fit properly together and have that button open and close the menu as a vertical list (even when it normally displays horizontally) and move the content down while the menu is open.

So that this will work even on touch screens we will use a hidden checkbox to keep track of whether the menu is open or closed and style the label for that checkbox as our button. As this is purely a hack to get our menu to be responsive on small touch screens we will not worry about the fact that having a checkbox outside of a form is not valid HTML as we are only using the checkbox to record whether the menu is open or closed on narrow screens and it isn't really part of a real form.

So that we can look just at the extra code needed to implement the menu button at narrower widths we'll assume that the menu already exists and has all the necessary CSS in place for it to function the way you want for wider viewports.

So here's the HTML we need to add in order to get our button to open and close the menu on narrow screens.

<label for="show-menu" class="show-menu">Show Menu</label>
<input type="checkbox" id="show-menu" role="button">

In this instance I have simply put the text "Show Menu" as what is to be displayed as the button but it is quite simple to substitute the usual 'hamburger' image for the text if that is what you prefer.

Next we need the CSS to hide this when the viewport is wide enough for both the menu and content to fit properly.

.show-menu {
/* other styles for the 'button' go here */
	display: none;
}

input[type=checkbox]{
    display: none;
}

We also need some CSS to make sure the menu is displayed if the checkbox is checked. The following assumes that the block of HTML containing the menu has an id="menu" on it.

input[type=checkbox]:checked ~ #menu{
    display: block;
}

Finally we need a media query to test for the appropriate width below which we want the button to display instead of the menu. Simply change the 760px to the width below which the button is to appear so as to toggle the menu instead of always displaying it.

@media screen and (max-width : 760px){
 #menu {
	display: none;
       }	
.show-menu {
	display:block;
       }
}

You may need to add some further CSS into the media query so that the menu is styled appropriately for narrower screens but these two HTML tags and five CSS commands are all that you need to add to your code in order to implement changing the menu into a 'button' at narrower widths and displaying and hiding the entire menu using that button.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate