Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating simple CSS multilevel menu

Tags:

css

I am trying to make a webpage with a navigation functionality EXACTLY like this one: http://www.rex-ny.com/ where you click a list item and its children items appear and stay.

I can do it with hover, but I can't figure out how to make it stay when not hovering.

It seems like the most simple thing is the most difficult to do.

<ul id="menu">
    <li><a href="#">Menu 1</a>
            <ul>
                <li><a href="#">Item A</a></li>
                <li><a href="#">Item B</a></li>
                <li><a href="#">Item C</a></li>
           </ul>
    </li>
    <li><a href="#">Menu 2</a>
            <ul>
                <li><a href="#">Item A</a></li>
                <li><a href="#">Item B</a></li>
                <li><a href="#">Item C</a></li>
           </ul>
    </li>
    <li><a href="#">Menu 3</a>
            <ul>
                <li><a href="#">Item A</a></li>
                <li><a href="#">Item B</a></li>
                <li><a href="#">Item C</a></li>
           </ul>
    </li>
</ul>

Thanks

Here is a jsfiddle http://jsfiddle.net/phzuC/

like image 257
user2730793 Avatar asked Oct 04 '22 02:10

user2730793


1 Answers

Here is a CSS only solution as the OP requested, using tabindex

DEMO http://jsfiddle.net/kevinPHPkevin/phzuC/2/

#menu li > ul {
    display:none;
}

#menu li:focus > ul {
    display:block;
}
li {
    outline: 0; 
}

EDITED

Here is a jQuery solution should you ever need it. It keeps the submenus open and it's simple to implement. 11 lines of code.

DEMO http://jsfiddle.net/kevinPHPkevin/phzuC/5/

 $(document).ready(function() {
  $(".nav-top > li").click(function(e) {
  if($(this).find('ul').hasClass('expanded')) {
      $(this).find('ul').removeClass('expanded').hide();
  } else {
    $(this).find('ul').addClass('expanded').show();
  }
  });
  $('.nav-top a').click(function(e){
    e.preventDefault(); 
  });
});
like image 169
Kevin Lynch Avatar answered Oct 08 '22 02:10

Kevin Lynch