Create an accordion menu with CSS only?

5

Accordion-style menus are useful for saving space, since you only open the parts with the content you need.

  

Exampleofmenuaccordionstyle

ButallofthesemenusoftenuseJavaScripttomakethesubtopics"shrink" and "expand" functionality. Is it possible to create this kind of CSS only functionality?

    
asked by anonymous 16.07.2014 / 23:46

1 answer

9
  

"Is it possible to create this kind of functionality with CSS only?"

Yes. You can achieve this effect with CSS using the tabindex HTML attribute.

HTML:

<ul class="menu-sanfona">
    <li tabindex="0">Item 1
        <ul>
            <li>Item 1.1</li>
        </ul>
    </li>
    <li tabindex="1">Item 2
        <ul>
            <li>Item 2.1</li>
        </ul>
    </li>
</ul>

And the CSS:

.menu-sanfona li ul{
    display:none;
}
.menu-sanfona li:focus ul{
    display:block;
}

More complete example: FIDDLE

What the code does is to use the tabindex attribute to make the li elements focusable, and then with CSS it is set that when li is in focus, ul child is visible .

Although this solution is interesting because it does not use JavaScript, it is somewhat limited, since the element is only open while it is in focus, ie if you click on some input or other item that has focus, the menu would close.

    
16.07.2014 / 23:46