Tips for hovering over child or nested <li> elements

Take a look at the provided code snippet below.

The structure is

<ul>
    <li>text1</li>
    <li> <ul><li> text2 </li>
             <li> text3 </li>
         </ul>
    </li>
</ul>

The CSS used is as follows:

li:hover
{
   background-color: yellow;
}

While this styling works correctly for the first li, when hovering over the second item (in the sub-ul), all items in the sub list are highlighted.

What I want is for only one row to be highlighted at a time, regardless of its relationship within the list items.

I attempted

li:only-child:hover

but it was unsuccessful. Many solutions on Stack Overflow suggest using jQuery to address this issue. Is there a way to resolve this using just CSS?

ul {
  list-style-type: none;
}
li:hover {
  color: blue;
  cursor: pointer;
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul>
  <li>Lv1: First Item</li>
  <li>Lv1: Second Item</li>
  <li>
    <ul>
      <li>Lv2: First Item</li>
      <li>
        <ul>
          <li>Lv3: First Item</li>
          <li>Lv3: Second Item</li>
          <li>Lv3: Third Item</li>
        </ul>
      </li>
      <li>Lv2: Second Item</li>
      <li>Lv2: Third Item</li>
    </ul>
  </li>

</ul>

Answer №1

To add the :hover property to a li element, it is recommended to wrap the text content in a surrounding element like this:

ul {
  list-style-type: none;
}
li span:hover {
  color: blue;
  cursor: pointer;
  background-color: yellow;
}
<ul>
  <li><span>Lv1: First Item</span></li>
  <li><span>Lv1: Second Item</span></li>
  <li>
    <ul>
      <li><span>Lv2: First Item</span></li>
      <li>
        <ul>
          <li><span>Lv3: First Item</span></li>
          <li><span>Lv3: Second Item</span></li>
          <li><span>Lv3: Third Item</span></li>
        </ul>
      </li>
      <li><span>Lv2: Second Item</span></li>
      <li><span>Lv2: Third Item</span></li>
    </ul>
  </li>
</ul>

(Alternatively, you can use div elements to highlight an entire row of content)

Answer №2

Feel free to customize the styles for list items inside unordered lists according to your preference:

ul {
    list-style-type: none;
    color: black;
    cursor: default;
    background-color: white;
}
li:hover {
    color: blue;
    cursor: pointer;
    background-color: yellow;
}
<ul>
    <li>Lv1: First Item</li>
    <li>Lv1: Second Item</li>
    <li>
        <ul>
            <li>Lv2: First Item</li>
            <li>
                <ul>
                    <li>Lv3: First Item</li>
                    <li>Lv3: Second Item</li>
                    <li>Lv3: Third Item</li>
                </ul>
            </li>
            <li>Lv2: Second Item</li>
            <li>Lv2: Third Item</li>
        </ul>
    </li>
</ul>

Answer №3

ul {
  list-style-type: none;
}
ul li:hover {
  color: blue;
  cursor: pointer;
  background-color: yellow;
}

ul li:hover ul{
  background-color: white;
  color: black;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul>
  <li>Lv1: First Item</li>
  <li>Lv1: Second Item</li>
  <li>
    <ul>
      <li>Lv2: First Item</li>
      <li>
        <ul>
          <li>Lv3: First Item</li>
          <li>Lv3: Second Item</li>
          <li>Lv3: Third Item</li>
        </ul>
      </li>
      <li>Lv2: Second Item</li>
      <li>Lv2: Third Item</li>
    </ul>
  </li>

</ul>

Make sure to reset for others while hovering.

Answer №4

To change the background color of nested lists, you can use the following CSS:

ul > li:hover {
  background: yellow;
}
ul > li:hover > ul {
  background: white;
}

Check out this example: http://jsfiddle.net/xo1g3sub/

Answer №5

I have included additional classes to help you target specific elements for styling purposes. For more information on this topic, you can visit > Is there a CSS selector for the first direct child only?

ul {
  list-style-type: none;
}
.first > li:hover {
  color: blue;
  cursor: pointer;
  background-color: yellow;
}
.first > .nested:hover{
 background:none;
 color:black;
}
<ul class="first">
  <li>Lv1: First Item</li>
  <li>Lv1: Second Item</li>
  <li class="nested">
    <ul>
      <li>Lv2: First Item</li>
      <li>
        <ul>
          <li>Lv3: First Item</li>
          <li>Lv3: Second Item</li>
          <li>Lv3: Third Item</li>
        </ul>
      </li>
      <li>Lv2: Second Item</li>
      <li>Lv2: Third Item</li>
    </ul>
  </li>
</ul>

Answer №6

If you're in search of a sophisticated solution that is driven by events, consider implementing the code snippet below:

Note: This code utilizes e.stopPropagation() to trigger events only on the hovered element. With just 2 event listeners, the entire list can be managed without needing any modifications to the HTML or CSS.

$('ul').delegate('li', 'mouseover', function (e) {
    if (e.currentTarget.tagName == 'LI') {
        $(e.currentTarget).css('background-color','yellow');
        e.stopPropagation();
    }
});

$('ul').delegate('li', 'mouseout', function (e) {
    if (e.currentTarget.tagName == 'LI') {
        $(e.currentTarget).css('background-color','');
        e.stopPropagation();
    }
});

Check out the working fiddle: https://jsfiddle.net/urahara/t6fp2un2/

Answer №7

<ul>
  <li>Level 1: First Item</li>
  <li>Level 1: Second Item</li>
  <li>Level 1: Third Item
    <ul>
      <li>Level 2: First Item</li>
      <li>Level 2: Second Item
        <ul>
          <li>Level 3: First Item</li>
          <li>Level 3: Second Item</li>
          <li>Level 3: Third Item</li>
        </ul>
      </li>
      <li>Level 2: Second Item</li>
      <li>Level 2: Third Item</li>
    </ul>
  </li>

</ul>


ul {
  list-style-type: none;
  position: relative; 
}
ul li:hover {
  color: blue;
  cursor: pointer;
  background-color: yellow;
}
ul > li{    
    display:inline-block;
}
ul li > ul{
    display:none;    
}

ul li > ul li{
    display:block; 
    color:#fff;
}
ul li:hover > ul{
  display: block;
  position: absolute;
  border: 1px solid #000;
  background:blue;  
}
ul li ul{
    position: relative;    
}
ul li ul li ul{    
    position: absolute;
    border: 1px solid #000;
    left: 100%;
}
ul li ul li:hover > ul {
  display: block;

}

View Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing and showcasing MySQL information using hidden forms

I'm facing an issue with displaying the selected data from MYsql. The values are stored in my database fields, and I want the review of the chosen movie to show up when the user clicks the submit button, but it's not working as expected. Below i ...

Is there a way to use PHP in place of the <form> tag in HTML in order to submit a form from a script and remain on

Currently, the code in my form looks like this: <form action="https://www.paypal.com/cgi-bin/webscr" target="_BLANK" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="paypal@ ...

Can a specific element be chosen based on its background color?

Is it possible to change the background color of a child element within a div that has a specific background color using CSS? See my explanation below. For example: .container[background-color=some color] .content { background-color: some other color ...

CSS for mobile devices not loading until the device is rotated

My website, redkrypt.com, is functioning perfectly on my laptop. However, I am facing an issue where the css file will only load on my iPhone 4S after I rotate it once. Once I do this, the website works both vertically and horizontally. I have tried variou ...

Issues with the HTML5 progress bar malfunctioning due to alterations made by Angular

Using the html5 progress bar <progress value="5" max="100"></progress> in angular can lead to it being replaced by angular classes. Angular also has its own progress bar that uses similar tags. However, elements like the html5 slider do not get ...

What is the best way to position this grid container directly beneath the search box using absolute positioning?

<!DOCTYPE html> <html lang="tr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Unique Starter</title> ...

What is the best location for storing css files in Laravel?

I've come to realize that I can easily make changes to the app.scss file in my Laravel projects and see those changes reflected by running npm run dev or npm run watch. However, I'm faced with a dilemma when dealing with multiple .css files. Whe ...

Implementing a Radial Cursor with a Custom Background Image in JavaScript

I am attempting to implement a radial cursor on a website that features a background image. Currently, I am facing two main issues: The radial cursor works in Chrome but not in Firefox. When using Firefox, I encounter a parsing error related to the "bac ...

Incorporate a pair of additional columns and showcase the outcome within a third column within an HTML

function = () => { var info1 = parseInt(document.getElementById("info1").value); var info2 = parseInt(document.getElementById("info2").value); var res = Number(info1.value + info2.value); var info3 = document.getElementById("info3"); ...

Customizing alert message styles in Java script: Changing color and font of specific parts

I have been attempting to change a specific part of text to be bold and displayed in red color. Unfortunately, this does not seem to work on Microsoft Edge. Here is my code: alert("Hi how are you my friend"); The section that needs to be formatted: "fri ...

Cube with 3D attributes and text displayed on each face shatters upon reaching a specific time limit on Google Chrome (between

The issue appears to be specific to Chrome. In Chrome, the 3D cube's face or multiple faces become transparent, giving the appearance that the animation is breaking. Sometimes adding "backface-visibility" after the break can temporarily resolve the is ...

What steps are needed to develop a proper HTML structure for this specific box in order to achieve the desired aesthetics?

Currently working on a box that includes various tags and an input field for adding new tags. The goal is to make this box resemble the tag form used on YouTube: https://i.stack.imgur.com/RSj2p.png This particular layout features a box with existing tags ...

JavaScript: Understanding the concept of closure variables

I am currently working on an HTML/JavaScript program that involves running two counters. The issue I am facing is with the reset counter functionality. The 'initCounter' method initializes two counters with a given initial value. Pressing the &a ...

Guide to implementing a seamless Vue collapse animation with the v-if directive

Struggling with Vue transitions, I am attempting to smoothly show/hide content using v-if. Although I grasp the CSS classes and transitions involved, making the content appear 'smoothly' using techniques like opacity or translation, once the anim ...

Tips for preventing redundancy in html theme construction by using bootstrap classes only once

As I embark on creating an HTML theme, I have decided to incorporate Bootstrap 4. One challenge I encountered was the need to repeat Bootstrap classes in various places, such as: <div class="row border border-top-0 mt-2 p-2 bg-info">One</div> ...

What caused the mat-date calendar style to malfunction?

I integrated mat-date into my Angular project, but encountered an issue where the styles of the calendar were not displaying properly when clicking the icon. Here is the displayed calendar effect I attempted to troubleshoot by commenting out the styles o ...

How can I send data to a Python script from a web application?

I have a Python script that requires 6 parameters to run, provided through the command line. python_file.py param1, param2, param3, param4, param5, param6 My goal is to pass these parameters from a web application built with Flask and Bootstrap. I want e ...

How come my web page is not displaying the guages from guage.js?

I am utilizing guage.js to create a graph based on this Fiddle. However, upon adding the same code to my website, the rendering does not appear as expected: https://i.sstatic.net/fIkQr.png Upon inspecting in Chrome developer tools, I noticed that the ele ...

CSS Priority - determining the ultimate winner

I have an upcoming exam and I'm reviewing the previous exam paper that was given to me. The question is: When multiple style sheet rules are applied to the same element, which type of rule takes precedence? a. Any declaration from the browser b. ...

Only wrap certain elements if they consist of two specific items

<div class="section"> <label>Title: </label> <input type="text" /> </div> <div class="section"> <label>Text: </label> </div> My goal is to enclose the label + input within an additional div ...