I have a navbar on a website, of which I want the background color to be yellow and text black. And when having a mouse over an item, the background would be black and the text yellow.
My problem is that the text is returning to black when moving the mouse outside of the text, but still within the boxed "li"-item, resulting in black background and black text. This causes problems for example where hovered dropdown title ("MORE") turns to black, and the background also remains in black when moving the mouse onto the listed items (see picture).
I know it’s because of "a = black" and "a:hover = yellow", so when the mouse is off the text ("a"), it returns to black, but I can’t get my head around on how to have the "a" remain yellow inside the hovered "li" item, even though the mouse is not on top of the text.
Note: I’m also using Spynav and StickNav on the website, which is the reason for the structure of my code. I just left them out to be more clear to read
Code:
<nav class="navbar">
<ul class="nav">
<li><a href="#">HOME</a></li>
<li><a href="#">CONTACT</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">MORE</a>
<ul class="dropdown-content">
<li><a href="discography">DISCOGRAPHY</a></li>
<li><a href="gallery">GALLERY</a></li>
<li><a href="videos">VIDEOS</a></li>
</ul>
</li>
</ul>
</nav>
.nav {
background-color: yellow;
}
.nav a{
color: black;
}
.nav a:hover{
color:yellow;
}
.nav li:hover{
background-color: black;
}
/* DROPDOWN MENU */
.dropdown-content {
background-color: yellow;
display: none;
position: absolute;
min-width: auto;
}
.dropdown:hover .dropdown-content {
display: block;
}
I have tried having the text color of hovered li-item to be yellow, and background black, as I’d love to think it would work like this.
.nav li:hover{
color:yellow !important;
background-color: black;
}
2
Answers
Change the selector
.nav a:hover
into.nav li:hover > a
Then each hovered menu item becomes yellow-on-black, and the items in the sub-menu stay black-on-yellow, until they themselves also get hovered. (That’s how you want it, right?)
html:
This is the fixed CSS. This works for me