Alim's Blog

πŸŽ‰Hello, welcome to my blog!πŸŽ‰

Find me on

Collapsible Menu using only CSS

24 Nov 2019|2 MIN READ

Collapsible menu is a very common component in a website. It is usually a list of items which can be expanded and collapsed by clicking on the menu title or icon. Watching the component we usually think it can only be done using javascript but the same functionality can be achieved using css only. For this reason we have to be a bit tricky.

At first we can simply add a list. Above it we will add a title. The HTML should look like following:

<label for="check-item">Click Me</label>
<input id="check-item" type="checkbox"/>
<ul>
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
  <li>Fourth</li>
  <li>Fifth</li>
</ul>

The first question here should be what is the necessity of a checkbox input? Actually here is the magic. Since we need to implement click action, only checkbox input can have checked selector. Now let us have a look at the CSS portion.

ul {
  list-style-type: none;
  height: 0;
  overflow: hidden;
  padding: 0;
}
input:checked + ul {
  height: 100%;
  overflow: visible;
}
#check-item {
  display: none;
}
label:hover {
  cursor: pointer;
}

We can very well see that initially the list is having height and its overflow is hidden. When the input is checked then the height is being showed. To make the click action work on the title we have given the input an id and used that id in the label. This is it. Without using any javascript we have implemented a collapsible menu.

Happy Coding πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€

Buy Me A Coffee

Share this on

Go back to home page

Created by M A Alim