user3321425
user3321425

Reputation: 201

h3 and list dropdown menu CSS3

got an html list working as a dropdown menu with CSS when you hover through a < li > element like "Products" in my example. But what I want is the same effect when hover through < h3 > like "Contact" from my example. Is it possible?

Here's the html:

<h3>Contact</h3>
 <ul>

    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li>
        <a href="#">Products &#9662;</a>
        <ul>
            <li><a href="#">Laptops</a></li>
            <li><a href="#">Monitors</a></li>
            <li><a href="#">Printers</a></li>
        </ul>
    </li>
    <li><a href="#">Contact</a></li>
</ul>

And the CSS code:

ul li ul {
    display: none;
}

ul li:hover ul{
    display: block; /* display the dropdown */
}

Thank you very much in advance.

Upvotes: 1

Views: 644

Answers (2)

oleynikd
oleynikd

Reputation: 932

In short - you should nest ul inside the h3

<h3>
    Contact
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li>
            <a href="#">Products &#9662;</a>
            <ul>
                <li><a href="#">Laptops</a></li>
                <li><a href="#">Monitors</a></li>
                <li><a href="#">Printers</a></li>
            </ul>
        </li>
        <li><a href="#">Contact</a></li>
    </ul>
</h3>

And in your css:

ul li ul {
    display: none;
}

ul li:hover ul{
    display: block; /* display the dropdown */
}
h3 > ul {
     display: none;
}
h3:hover > ul {
    display: block;
}

Here's the demo: https://jsfiddle.net/mscehjLf/1/

Upvotes: 1

Jasper
Jasper

Reputation: 630

On hover you can only control the CSS of the element you hover over, or the CSS of elements within the element you hover over (one of its children). So you can not make the ul change styles when you hover over the h3 because they 1) are not the same object and 2) do not have a parent-child relationship (they are siblings).

To show the menu when hovering over the h3, you can wrap both of them inside another object (div) and use this for the hover event. To distinguish between the two hovers you can add classnames to both the uls.

See this JSfiddle, or the code below:

<div class="container">
    <h3>Contact</h3>
    <ul class="menu">
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li>
            <a href="#">Products &#9662;</a>
            <ul class="submenu">
                <li><a href="#">Laptops</a></li>
                <li><a href="#">Monitors</a></li>
                <li><a href="#">Printers</a></li>
            </ul>
        </li>
        <li><a href="#">Contact</a></li>
    </ul>
</div>
.container ul{
    display: none;
}
.container:hover ul.menu{
    display: block;
}
ul li ul.submenu {
    display: none;
}

ul li:hover ul{
    display: block; /* display the dropdown */
}

Upvotes: 1

Related Questions