I have a nested list:
li:hover {
background-color: lightgray;
}
ul li ul li:hover {
font-weight: bold;
}
<ul>
<li>fnord
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
<li>gnarf
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>yolo</li>
</ul>
</li>
</ul>
</li>
</ul>
Problem is, hovering "foo" will also hover "fnord" and all of its li
elements. How do I hover only the li
my mouse is actually hovering over?
The nesting is variable and can, in theory, be endless.
I have setup a JSFiddle.
The :hover selector is used to select elements when you mouse over them. Tip: The :hover selector can be used on all elements, not only on links. Tip: Use the :link selector to style links to unvisited pages, the :visited selector to style links to visited pages, and the :active selector to style the active link.
You can create a nested unordered list, or a nested ordered list, or even an ordered list nested inside an unordered one. Remember that the only direct child of the ul tag is li . You create the nested unordered list under the main list's item of your choosing.
I believe the closest you can get with just CSS is to remove the hover styling from the children of the hovered elements... which doesn't help the parents.
li:hover {
background-color: lightgray;
}
li:hover {
font-weight: bold;
}
li:hover ul {
background-color: white;
font-weight: normal;
}
<ul>
<li>fnord
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
<li>gnarf
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
</ul>
JSFiddle
The accepted answer on the duplicate you found is the best way I've seen to do this with JavaScript, using e.stopPropagation
: Cascading <li>-hover effect using CSS. You'll want to be more specific than 'all lis' in that selector though:
$('li').mouseover(function(e)
{
e.stopPropagation();
$(this).addClass('currentHover');
});
$('li').mouseout(function()
{
$(this).removeClass('currentHover');
});
.currentHover {
background-color: red;
}
li.currentHover ul {
background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li>fnord
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
<li>gnarf
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
</ul>
JSFiddle of the answer from there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With