E.Cross
E.Cross

Reputation: 2137

nav menu won't expand

I have a vertical navigation menu and I want to show different levels of the menu upon hovering of certain elements. The problem is that the method I used is not working and I do not understand why. When I hover over "Product", I expect to see a sub-menu expand, but nothing happens. Why?

HTML:

<nav>
<ul>
<li><a href="./index.html">Home</a></li>
<li><a href="./about.html">About</a></li>
<li><a href="./product.html">Product</a></li>
       <ul>
       <li><a href="#">Blueberries</a></li>
       <li><a href="#">Rasberries</a></li>
       <li><a href="#">Strawberries</a></li>
       </ul>
<li><a href="./contact.html">Contact</a></li>
</ul>
</nav>

CSS:

nav {
border:1px solid red;
}
nav ul ul {
display:none;
}
nav ul li:hover > ul {
display:block;
}

Upvotes: 1

Views: 364

Answers (4)

Gimmy
Gimmy

Reputation: 3911

Try this for your html:

<nav>
<ul>
    <li><a href="./index.html">Home</a></li>
    <li><a href="./about.html">About</a></li>
    <li><a href="./product.html">Product</a>
        <ul>
            <li><a href="#">Blueberries</a></li>
            <li><a href="#">Rasberries</a></li>
            <li><a href="#">Strawberries</a></li>
        </ul>
    </li>
    <li><a href="./contact.html">Contact</a></li>
</ul>
</nav>

Upvotes: 1

Crispen Smith
Crispen Smith

Reputation: 533

You have two ways of changing this; you can either update the HTML or you can update the CSS.

There are pros and cons to changing code and in a vacuum I can't recommend one approach over the other.

Without changing your HTML you can make the CSS work like this:

nav ul li:hover + ul {
  display: block;
}

Note that rather than using the descendant selector this uses the adjacent selector and applies the style to the element that immediately follows the hovered LI.

Alternatively, the HTML change mentioned above does work equally well.

This link http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/ provides a fantastic resource.

Upvotes: 0

Nick
Nick

Reputation: 4212

Also

nav ul ul {
   display:none;
}

should be

nav ul li ul {
display:none;
}

Upvotes: 1

Richard
Richard

Reputation: 30618

Your code:

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

Means "Make any ul within a hovered li display:block". Your submenu is not within the LI, it's after it. Here's a working version of what you were trying to do.

Working HTML:

<li><a href="./product.html">Product</a>
       <ul>
       <li><a href="#">Blueberries</a></li>
       <li><a href="#">Rasberries</a></li>
       <li><a href="#">Strawberries</a></li>
       </ul>
</li>

Working CSS:

nav ul li ul {
    display:none;
}
nav ul li:hover ul {
    display:block;
}

Upvotes: 3

Related Questions