Cody Reandeau Cody Reandeau - 1 month ago 11
HTML Question

Hover over menu item, sub-menu fades in then disappears

When I hover over a menu item I want the sub-menu to fade in. I have in fact gotten it to do that. However, when I attempt to click on one of the sub-menu options, the sub-menu disappears before I have any time to click a sub-menu item.

Here is the html for the navigation menu:

<div id="nav">
<ul>
<li><a href="./index"><div>About Me</div></a>
<ul>
<li><a href="./index">Bio</a></li>
<li><a href="./Resume">Resume</a></li>
</ul>
</li>
<li><a href="https://github.com/user_name" target="_blank"><div>Github</div></a></li>
</ul>
</div>
</div>


Here is the accompanying css for the navigation and the sub-menu:

#nav {
background-color: #F8F8F8;
padding-right: 45px;
}

#nav ul {
position: relative;
margin: 10px;
font-family: 'Crete Round';
font-size: 20px;
font-weight: bold;
list-style-type: none;
float:right;
top:22px;
}

#nav ul li {
display: inline-block;
}

#nav ul li a:hover {
color: #33CCCC;
}

#nav ul li a, visited{
margin:10px;
display: block;
text-decoration: none;
text-align: left;
}

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

#nav ul ul {
display:none;
position:absolute;
background-color: #F8F8F8;
z-index:100;
padding-left: -25px;
border: 2px solid #F2F2F2;
border-top: 0;
margin-top: 12px;
}

#nav ul ul li {
display: block;
width:100px;
margin-left:-40px;
}

#nav ul ul li:hover {
background-color: #505050;
}

#nav ul ul li a:hover {
color:white;
}

#nav ul li:hover > ul {
opacity: 0;
-webkit-animation: fadein 2s; /* Safari and Chrome */
-moz-animation: fadein 2s; /* Firefox */
-ms-animation: fadein 2s; /* Internet Explorer */
-o-animation: fadein 2s; /* Opera */
}

@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}


Any nudge into the right direction would be greatly appreciated.

Answer

Using keyframes won't save final animation state by default. So it goes back to opacity: 0. You have to use animation-fill-mode with forwards value to save it (see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode).

Usage:

#nav ul li:hover > ul {
opacity: 0;
-webkit-animation: fadein 2s forwards; /* Safari and Chrome */
-moz-animation: fadein 2s forwards; /* Firefox */
-ms-animation: fadein 2s forwards; /* Internet Explorer */
-o-animation: fadein 2s forwards; /* Opera */
}

You can also omit opacity: 0 as far as that element is not visible until hover anyways, that should work too.