This site uses third-party cookies, learn more or accept
dark light

Pure CSS collapsible menu

Written by Max Pelic on

In this tutorial, I'll show you how to create a collapsible HTML menu using CSS only (no JavaScript).

Here's an example of what we'll be making:

View on CodePen

Step 1: The HTML

To create a menu, we'll use a checkbox to keep track of the state of the menu (open or collapsed) and a ul for the list of links. We'll use a label to display the icon for the menu, either a burger icon or a close button.

Here's the HTML we'll be using:

1<nav>

2 <input type="checkbox" id="menuToggle">
3 <label for="menuToggle"><span>&times;</span><span>&#9776;</label>
4 <ul>
5 <li><a href="#home">Home</a></li>
6 <li><a href="#about">About</a></li>
7 <li><a href="https://maxpelic.com" target="_blank">Developer</a></li>
8 </ul>
9</nav>

Next, let's start adding the CSS...

Step 2: CSS

We'll start by adding the core functionality to the menu, and then we can add some style to it.

First, let's hide the checkbox element. We'll only use it to keep track of the state of the menu, so we don't need the user to see it.

1nav input{

2 display:none;
3}

Next, we'll hide the menu icon when the menu is open, and hide the close icon when the menu is closed. We'll use the sibling combiner ~ to change the visibility when the checkbox is checked.

1nav input:checked ~ label span:last-child{

2 display:none;
3}
4nav input:not(:checked) ~ label span:first-child{
5 display:none;
6}

Let's position the menu in the top left corner of the page. We'll also hide any overflow so the options aren't displayed when it's collapsed.

1nav{

2 position:fixed;
3 top:20px;
4 left:20px;
5 min-width:40px;
6 min-height:40px;
7 overflow:hidden;
8}

Last but not least, we'll make the menu expand and collapse depending on the state of the checkbox. We'll also set some basic styling to make it look like a menu.

1nav ul{

2 overflow:hidden;
3 width:0;
4 height:0;
5 padding:0;
6 margin:0;
7 transition:width 0.5s, height 0.5s;
8 list-style:none;
9}
10nav input:checked ~ ul{
11 width:200px;
12 height:90px;
13}

That's it for the basic functionality. You can check out the CodePen example for some styling ideas.

You can email me with any feedback/questions at max@maxpelic.com

Share this article:

Previous Article: Password show/hide animation

Next Article: Simple JavaScript Parallax