Create collapsing sub-menus with CSS & WordPress 3.0
-
I had a tough time figuring out the CSS for creating collapsing sub-menus with the new WordPress menu system, so I though sharing this code would be helpful. This was originally posted on my blog at https://daltonrooney.com/wordpress/archives/173
WordPress has lots of CSS hooks for current pages, parent pages, current page ancestor pages, etc… to the point where it can get very hard to keep the hierarchy straight. Here’s the code I came up with:
.widget_nav_menu ul.sub-menu { display: none; } .widget_nav_menu .current_page_parent ul.sub-menu { display: block; } .widget_nav_menu .current_page_ancestor ul.sub-menu { display: block; } .widget_nav_menu li.current-menu-item ul.sub-menu { display: block; } .widget_nav_menu ul.sub-menu li.current-menu-item ul.sub-menu { display: block; } .widget_nav_menu ul.sub-menu ul.sub-menu { display: none; } .widget_nav_menu ul.sub-menu li.current_page_ancestor ul.sub-menu { display: block; } .widget_nav_menu a { color: #666666; } .widget_nav_menu li.current-menu-item a { color: #222222; } .widget_nav_menu li.current-menu-item ul.sub-menu a { color: #666666; }
You can obviously combine most of these selectors, but I prefer to keep them separate to make it easier to troubleshoot. I added a different color border around each element while I was working on it so I could quickly see exactly which styles were being applied.
I should also note that this was developed specifically for the Custom Menus widget (hence the .widget_nav_menu classes), so you should adjust this to match your menu container div if you insert your menus another way.
- The topic ‘Create collapsing sub-menus with CSS & WordPress 3.0’ is closed to new replies.