Boardy
Boardy

Reputation: 36225

Display a ul class when the mouse hovers over a li class css only

I am currently looking into developing a CSS only drop down menu. The idea is when the mouse hovers over a ul tag it will make another ul class appear.

Below is the code that I currently have.

HTML

<head>
<link href="nav.css" rel="stylesheet" type="text/css">
</head>

<ul class="nav">
    <li class="topMenu"><a href="#">Home</a></li>
    <ul class="subMenu" id="home">
        <li><a href="#">Hello</a></li>
        <li><a href="#">World</a></li>      
    </ul>
</ul>

CSS

.nav, .topMenu, .subMenu
{
    position: relative;
    list-style: none;
}

.topMenu
{
    position: relative;
    float: left;
}

.subMenu
{
    display: none;
}

.topMenu a:hover + li
{
    display: block;
    background-color: blue;
}

The idea is that when the mouse hovers over the li class="topMenu" then the ul class="subMenu" id="home" should appear underneath.

Ideally this should be only in a CSS format without requiring any javascript etc.

Thanks for any help you can provide.

Upvotes: 1

Views: 48781

Answers (2)

Wex
Wex

Reputation: 15695

All you really need to do is nest the <ul> within your <li> element.

<nav>
    <ul>
        <li><a href="#">Link</a></li>
        <li>
            <a href="#">Link</a>
            <ul>
                <li><a href="#">Submenu</a></li>
                <li><a href="#">Submenu</a></li>
            </ul>
        </li>
        <li><a href="#">Link</a></li>
    </ul>
</nav>

Here's some CSS that will help you get started:

/* Resets */
nav a { 
    text-decoration: none;
    font: 12px/1 Verdana;
    color: #000;
    display: block; }
nav a:hover { text-decoration: underline; }
nav ul { 
    list-style: none;
    margin: 0;
    padding: 0; }
nav ul li { margin: 0; padding: 0; }

/* Top-level menu */
nav > ul > li { 
    float: left;
    position: relative; }
nav > ul > li > a { 
    padding: 10px 30px;
    border-left: 1px solid #000;
    display: block;}
nav > ul > li:first-child { margin: 0; }
nav > ul > li:first-child a { border: 0; }

/* Dropdown Menu */
nav ul li ul { 
    position: absolute;
    background: #ccc;
    width: 100%; 
    margin: 0;
    padding: 0;
    display: none; }
nav ul li ul li { 
    text-align: center;
    width: 100%; }
nav ul li ul a { padding: 10px 0; }
nav ul li:hover ul { display: block; }

Preview: http://jsfiddle.net/Wexcode/BEhvQ/

Upvotes: 4

bookcasey
bookcasey

Reputation: 40473

It will need some tweaking:

<ul class="nav">
    <li class="topMenu"><a href="#">Home</a></li>
    <li class="subMenu">
    <ul id="home">
        <li><a href="#">Hello</a></li>
        <li><a href="#">World</a></li>      
    </ul>
    </li>
</ul>


.topMenu:hover + .subMenu
{
    display: block;
    background-color: blue;
}

Demo

Upvotes: 2

Related Questions