Jump to the content of the page

Is it possible to create an off-canvas menu without JavaScript?

Schwarz-Weiß-Foto aus dem Photo Archiv Schweitzer: Mann schaut durch winzige Lupe

Yes! JavaScript is usually used to control the status of an HTML element using other elements. However, there is also a simple trick you can use to control flyout menus, accordions and collapsible elements using only CSS.

 

 

CSS3 instead of JavaScript

You can create an off-canvas menu without JavaScript by using a clever combination of pseudo-classes and sibling combinators. A simple HTML checkbox is used to affect the navigation status.

In addition to reducing JavaScript, which often leads to improved loading time, this also optimises accessibility as a checkbox can be controlled in all browsers using the keyboard and mouse clicks and can be read well using screen readers.

General sibling combinators

The sibling combinators “+” and “~” are often neglected but are quite helpful. They can be used to determine HTML elements based on the influence of parent elements. Particularly when used in modular templates and frameworks, they make it possible to integrate smart and intelligent solutions into the layout by enabling elements to be styled based on their order in the DOM. 

 

“:checked” pseudo-class:

The :checked pseudo-class can be used for “checkbox” and “radio” input types. Similar to a :hover pseudo-class, this combined CSS selector is only active if the checkbox has been selected. This happens independent of the value of the input element.

“:target” pseudo-class

The “:target” pseudo-class can be used as an alternative to similar effect. In this case, attention should be paid to the fact that only one individual value can be used as a fragment identifier in the URL. Unlike menus across several possible levels, this could provide the perfect effect when used in an accordion, for example.

 

Jump up Hide the menu