Create a "accordion" menu with CSS only?

Asked

Viewed 9,979 times

5

Menus in style accordion (accordion) are useful for saving space, since you only open the parts with the content you need.

Exemplo de menu sanfona Example of style menu accordion.

But all of these menus usually use Javascript to make the functionality "contract" and "expand" the subitens. It is possible to create this type of functionality only with CSS?

1 answer

9


"It is possible to create this type of functionality only with CSS?"

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

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;
}

Most complete example: FIDDLE

What the code does is use the attribute tabindex to make the elements li can be focused, and then with CSS is defined that when the li is focused, the ul his son becomes visible.

Although this solution is interesting for not using Javascript, it is a little limited, since the element is only open while it is focused, IE, if you click on some input or another item that has focus, the menu would close.

  • very good! Using css3’s to make up slow sliding effect, leave this option for others to get an extra knowledge!!

  • A question why when I insert a link it closes the square and is not redirected to the page? Great tip! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.