Guide to altering the color of a list item when hovering in HTML

Is there a way to change the color of the <li> element only when hovering over it, without affecting its parent or child elements?

Here is an example:

HTML:

<div id="tree">
<ul>
    <li>apple</li>
    <li>banana</li>
    <li>mango
        <ul>
            <li>date</li>
            <li>pear</li>
            <li>fig</li>
        </ul>
    </li>
</ul>

CSS:

#tree > ul > li:hover {
   background:brown;
}
#tree > ul > li:hover > ul >li{
   background:white;
}
#tree > ul > li > ul > li:hover {
   background:yellow;
}

https://jsfiddle.net/1v57nwg8/

If you have any suggestions using css, javascript, or jquery, they would be greatly appreciated.

Answer №1

Enclose the text content of LIs in a SPAN or equivalent:

Here is an example in HTML:

<div id="tree">
    <ul>
        <li><span>apple</span></li>
        <li><span>banana</span></li>
        <li><span>mango</span>
            <ul>
                <li><span>date</span></li>
                <li><span>pear</span></li>
                <li><span>fig</span></li>
            </ul>
        </li>
    </ul>
</div>

And the corresponding CSS:

#tree > ul > li:hover > span {
   background:brown;
}
#tree > ul > li > ul > li:hover > span {
   background:yellow;
}

Answer №2

If I understand your question correctly, it seems like you want to apply a specific background rule for the child ul element so that it doesn't inherit the color from its parent li:

#tree > ul > li:hover > ul {
   background:white;
}

Check out this Live Example:

#tree > ul > li:hover {
   background:brown;
}
#tree > ul > li:hover > ul >li{
   background:white;
}
#tree > ul > li > ul > li:hover {
   background:yellow;
}
/* The new rule goes here: */
#tree > ul > li:hover > ul {
   background:white;
}
<div id="tree">
    <ul>
        <li>apple</li>
        <li>banana</li>
        <li>mango
            <ul>
                <li>date</li>
                <li>pear</li>
                <li>fig</li>
            </ul>
        </li>
    </ul>
</div>

Answer №3

Give this a shot:

#forest > ul > li:hover > div {
   background:green;
}
#forest > ul > li > ul > li:hover {
   background:orange;
}
<div id="forest">
<ul>
    <li><div>oak</div></li>
    <li><div>maple</div></li>
    <li><div>pine</div>
        <ul>
            <li>birch</li>
            <li>spruce</li>
            <li>cedar</li>
        </ul>
    </li>
</ul>

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

Is it possible to close the menu by clicking outside a div or letting it disappear on mouseout after a set period of time?

When visiting a website, you may notice menus that display sub-menus when hovered over. These menus and sub-menus are created using div elements, with the sub-menus hidden initially using style.display = none; The issue arises when a sub-menu is opened an ...

Tips for inserting a logo in the center of a QR code using Node.js

I'm currently working on designing a logo and attempting to incorporate it into the center of a QR code. While I've been successful in generating the QR code, I'm facing challenges in getting the logo to appear in the middle. I've tried ...

Multiple File Select Upload Tool

I'm currently stuck trying to brainstorm a practical solution for enabling users to upload multiple files with ease. However, I'm facing some challenges... The requirement is for the user to be able to select several files at once in the file d ...

Having trouble identifying the CSS style being applied to a specific element

In this image, a red border is seen on the input fields indicating an error with some CSS style being applied. Despite this, it is difficult to determine which CSS selector is causing this as Firebug does not reveal any applied styles. https://i.stack.img ...

Identify matching values in objects and dynamically update them with a custom value

I have an array structured like this: var array = [ { dates: "2020-12-25", class: "first" }, { dates: "2020-12-26", class: "last" }, { dates: "2021-06-11", class: "first" }, ...

Tips for creating a dynamic header background using custom CSS for my website design

As I embark on creating my very first WordPress website using the Blossom Pin Pro theme, I'm encountering an issue where the background image of the header disappears when adjusting the window width. Click here to visit the site If you have a code s ...

Adjust the camera in threejs to be positioned inside a different object

My goal is to adjust the camera controlled by trackballControl to match the position of an object. Currently, it's functioning correctly but as demonstrated in this example, each time the camera changes its position, the z value also changes, which i ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

Uploading a CSV file in JSON format to Amazon S3 with Node.js

Within my nodejs server.js script, the following code snippet can be found: router.post('/submission', (req, res) => { let data_filtered = req.body.data }) Upon user submission of a csv file, I am successfully retrieving it on the backend. ...

How can you add an error notification to a click on a protractor?

Is there a method to associate an error message with a protractor click function? I am envisioning something like the example line below: button.click('Button not clickable'); Currently, when an element cannot be located, I receive the non-spec ...

Material UI Grid List rows are displaying with an unusually large gap between them, creating a

Currently, I am utilizing Material UI in combination with Reactjs. One particular issue that I am encountering involves the Grid List Component. In my attempt to establish a grid of 1000x1000px, I have specified the height and width within the custom gridL ...

Ways to prevent image toggling when the mouse moves out of it or when the hover effect stops

I'm looking to toggle between two images on mouseover/hover and stop the toggling when hovering stops. Here is the HTML code I have: <div class="fader"> <img src="image1" /> <img src="image2" /> </div> This is the JQuery ...

Identifying the moment a member receives a role using my Discord bot built with discord.js

I am currently working on detecting when a user is assigned a specific role on a server. Here is the code I have been using: // Require the required discord.js classes const { token } = require('./config.json'); // Create a new client instance ...

Validating HTML Forms Using PHP

I am experimenting with a basic HTML login form, but I can't seem to get it to function properly. This is all new to me as I am just starting out with PHP programming. Any assistance would be greatly appreciated! <?php $correctPassword = 'ho ...

Ensure proper tagging by adding a closing tag to the HtmlElement in HtmlUnit

I am looking to convert an Html page to pdf, but the HtmlPage contains many unclosed tags like: < hr > < br > Because of these unclosed tags, I am unable to create a Pdf. Is there a way to close these tags using HtmlUnit in Java? What I need ...

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

The Mongoose findOneAndUpdate method will only return the newly added document when using the $push

Provided here is a structured representation of my "profile" collection: { _id : ObjectId("2bb0fad110"), name : "Tommy", defaultrates : [ {_id : ObjectId("444cbcfd52"), rate : 35.0, raisedOn : "5/2/2009"}, {_ ...

best practices for data flow between components in React using hooks

I have successfully retrieved data from my database in the Recipes component. Now, I am attempting to pass this data into the RecipeList component. However, when I do so, only the bullet points are showing up in the RecipeList component and for some reas ...

What is the process of redefining the toString method for a function?

I am currently tackling a coding challenge that involves chaining functions. While researching possible solutions online, I noticed that many of them involved using function.toString and overriding the toString method of a function to create a chained add ...

What is the method for embedding HTML content into the header section of tcpdf?

I am currently utilizing the tcpdf library to create a PDF document. I have implemented the smarty template engine to manage the data. Below is the code snippet for inserting header data: // set default header data $pdf->SetHeaderData(PDF_HEADER_LOGO, ...