Tony D.
Tony D.

Reputation: 560

Submenu vanishes after mouse off main menu item

Could someone explain to me why navigating away from the main menu item causes the sub-menu to vanish? And possibly provide a fix. My google-foo skills are below par this morning. Thanks all.

CSS:

body, html{
        margin: 0;
    }

    .content{
        padding: 30px;
    }

    .nav-main{
        width: 100%;
        background-color: #222;
        height: 70px;
        color: #fff;
    }

    .nav-main > ul{
        margin: 0;
        padding: 0;
        float: left; 
        list-style-top: none;
    }

    .nav-main > ul > li {
        float: left;
    }

    .nav-item {
        display: inline-block;
        padding: 15px 20px;
        height: 40px;
        line-height: 40px;
        color: #fff;
        text-decoration: none;
    }

    .nav-item:hover{
        background-color: #444;
    }

    .nav-content{
        position: absolute;
            top: 70px;
            overflow: hidden;
            background-color: #222; /* same color as main nav*/
            max-height: 0; /*will not display if .nav-content no padding */
    }

    .nav-content a{
        color: #fff;
        text-decoration: none;
    }

    .nav-content a:hover{
        text-decoration: underline;
    }

    .nav-sub{
        padding: 20px;
    }

    .nav-sub ul{
        padding: 0;
        margin: 0;
        list-style-type: none;
    }

    .nav-sub > ul > li{
        display: inline-block;
    }

    .nav-sub ul li a{
        padding: 5px 0;
    }

    .nav-item:focus{
        background-color: #444; /*remove if click focus not necessary*/
    }

    .nav-item:hover ~ .nav-content{ 
        max-height: 400px;
        -webkit-transition:max-height 0.6s ease-in;
        -moz-transition:max-height 0.6s ease-in;
        transition:max-height 0.6s ease-in;
    }

HTML:

<body>
    <nav class="nav-main">
        <ul>
            <li>
                <a href="#" class="nav-item">first</a>
                <div class="nav-content">
                    <div class="nav-sub">
                        <ul>
                            <li><a href="#">this is a thing</a></li>
                            <li><a href="#">this is a thing 2</a></li>
                        </ul>
                    </div>
                </div>
            </li>
            <li>
                <a href="#" class="nav-item">second</a>
            </li>
            <li>
                <a href="#" class="nav-item">third</a>
            </li>
        </ul>
    </nav>

    <div class="content">this is content</div>
</body>

Upvotes: 1

Views: 29

Answers (1)

Alon Eitan
Alon Eitan

Reputation: 12025

I have changed:

.nav-item:hover ~ .nav-content{ 

To

nav > ul > li:hover > .nav-content{ 

And now it's working - example: https://jsfiddle.net/saxkayv2/

Upvotes: 1

Related Questions