0

got a nested LI menu - what I want to be able to do is show all child ULs when any parent LI is hovered over. Ideally in just CSS? but jQuery is OK if not poss in CSS.

Menu code is:

<ul>
<li><ahref="#">Item 1</a>
<ul>
<li><ahref="#">Sub Item 1</a></li>
<li><ahref="#">Sub Item 2</a></li>
<li><ahref="#">Sub Item 3</a></li>
</ul>
</li>
<li><ahref="#">Item 2</a>
<ul>
<li><ahref="#">Sub Item 1</a></li>
<li><ahref="#">Sub Item 2</a></li>
<li><ahref="#">Sub Item 3</a></li>
</ul>
</li>
</ul>

So for example - when Item 1 is hovered over - the submenu ULs for Item 1 AND Item 2 should show... easy? I cant seem to work it out.... :(

2
  • What's your existing (relevant) CSS? Mar 7, 2014 at 15:10
  • No - not a duplicate question. The difference here is i want ALL child ULs to show on hover of any parent LI...
    – dubbs
    Mar 7, 2014 at 15:18

1 Answer 1

2

Under your current requirements, that the hover of the <li> should show the <ul> child elements of all sibling <li> elements this isn't possible without JavaScript (with or without a library, as CSS lacks the ability to select elements appearing previously in the DOM, including both ancestor-elements and previous siblings); however if you're willing to allow for the hover to take place on the parent <ul> element this becomes possible with simple CSS:

ul > li {
    display: list-item;
}

li > ul {
    display: none;
}

ul:hover > li > ul {
    display: block;
}

JS Fiddle demo.

In the above the use of the child combinator (>) means this will show only the first level of <ul> elements, if that last rule is amended then all <ul> children can be shown:

ul:hover > li ul {
    display: block;
}

JS Fiddle demo.

5
  • Jheeze! Nice work. I'm deleting my answer and +1'ing.
    – Albzi
    Mar 7, 2014 at 15:43
  • @BeatAlex: thanks! But, I'm not sure this is significantly better than your own answer. Mar 7, 2014 at 15:44
  • P.S. I assume this wont work well in old IE though > is not supported is it? What would be the jQuery more universal solution to achieve the same end result?
    – dubbs
    Mar 7, 2014 at 15:45
  • It's supported in IE 7 and above (source: http://www.quirksmode.org/css/selectors/#t10); honestly, I'd recommend not even bothering with IE 5.5 or 6; they cost more to accommodate than will ever be justified by recompense from that support. Similarly, of course, those browsers also fail to recognise :hover on any elements other than <a>. Mar 7, 2014 at 15:48
  • This is awesome. Thanks for this answer!
    – mnutsch
    Mar 21, 2017 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.