How to make a menu have submenus in pure CSS

前端 未结 3 1025
孤独总比滥情好
孤独总比滥情好 2021-01-03 16:51

I want to know if i can get the ul class productnav to dissappear until the mouse hovers over the product button? Also, I want the productnav ul to go off to the side like a

3条回答
  •  無奈伤痛
    2021-01-03 17:30

    With ul.menu being the parent of all the others, but differing from your html approach in this : the submenus (ul tags) are inside a parent's menu item (li tag), which is more consistent with html requirements (a w3 recommendation, a question, or just test it in the validator). So your example would become the following :

    And the css I would use (even though you could strip the sizes, as long as they're all the same, I think) :

    .nav li
    {
        position:relative;
        float:left;
        width:180px;
        height:30px;
        padding:0;
        margin:0;
        list-style: none;
    }
    
    .nav ul
    {       
        display:none;
        position:absolute;
        padding:0;
        margin:5px 0 0 0;
    }
    
    .nav ul li ul
    {
        left:100%;
        top:0;
        margin:0px;
    }
    
    /* hiding or showing on second generations */
    .nav li:hover ul ul, .nav li:hover ul ul ul
    {
        display: none;
    }
    
    .nav li:hover ul, .nav ul li:hover ul, .nav ul ul li:hover ul
    {
        display: block;
    }
    

    This works on up to three recursive levels of uls in your ul.nav, but you could expand it as much as you'd want by modifying the selectors of the two last css blocks.

    But I still think that replacing the :hover with a .over class that appears on hover with hover events in javascript gives a better feeling, because you can set a timeout to keep the menu shown for a short moment after having hovered it. Allows for more natural moves with your pointer when navigating to a sub-menu, with the css approach you have to stay inside the li tags.

提交回复
热议问题