[SOLVED] How to hover only the current li in nested ul?

Issue

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.

Solution

A solution for subitems and also for parents is possible without JavaScript, when you will add some inline element, which will trigger hover state.

li>span:hover {
   background-color: lightgray;
   font-weight: bold;    
}
<ul>
    <li><span>fnord</span>
        <ul>
            <li><span>baz</span></li>
            <li><span>foo</span>
                <ul>
                    <li><span>baz</span></li>
                    <li><span>foo</span></li>
                </ul>
            </li>
        </ul>
    </li>
</ul> 

JSFiddle here.

Answered By – Kolman Robert

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *