Creating a Hamburger Menu (Checkbox Hack)

A "hamburger" menu is an icon consisting of three horizontal lines (☰) that expands to reveal navigation links when tapped. You can create a fully interactive hamburger menu using HTML and CSS without writing a single line of JavaScript.

Typically, making a button click open a menu requires scripting. However, by using a clever CSS technique known as the "checkbox hack", we can use an HTML form checkbox to keep track of whether our menu is open (checked) or closed (unchecked).

The HTML Structure

To make this work, we need a hidden input element of type="checkbox", and a label element tied to it. When the user taps the label (which we will style to look like the hamburger icon), it will secretly check the hidden checkbox:

The CSS Magic

On large screens, we use display: none; to hide both the checkbox and the label icon so the user just sees a normal row of links.

When the screen becomes smaller, our CSS media query takes over. It hides the normal .nav-links list, and reveals the label icon.

The main part is done using the CSS general sibling combinator (~). We tell CSS that if the #menu-toggle checkbox is checked, find the sibling .nav-links list below it, and change its display back to flex (visible):

Full Working Example

Below is a complete, functioning responsive menu. Try resizing your browser window until you see the hamburger icon. Click the icon to see the invisible checkbox toggle the menu on and off:

View Output Full Screen Preview

Tip: Using JavaScript

While the pure CSS checkbox hack is brilliant and lightweight, most large, complex production websites eventually handle their mobile menus (and animations) using a small snippet of JavaScript instead, simply adding or removing an "open" CSS class to the menu container when a button is clicked. See How to Create a Hamburger Menu for an example of this in action.