简体   繁体   中英

How to change the color of li elment on hover in html?

I want to change the color of <li> element on hover. problem is that when I hover on child li elements, the color of parent <li> element also getting change.

See following 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/

Any help using css, javascript or jquery appreciated.

Put a SPAN or something else around the text content of the LIs:

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>

CSS:

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

If I'm guessing at your question correctly, you need to add a rule for the child ul so its background doesn't inherit its color from its parent li :

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

Live Example :

 #tree > ul > li:hover { background:brown; } #tree > ul > li:hover > ul >li{ background:white; } #tree > ul > li > ul > li:hover { background:yellow; } /* This is the new rule: */ #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> 

Try this:

 #tree > ul > li:hover > div { background:brown; } #tree > ul > li > ul > li:hover { background:yellow; } 
 <div id="tree"> <ul> <li><div>apple</div></li> <li><div>banana</div></li> <li><div>mango</div> <ul> <li>date</li> <li>pear</li> <li>fig</li> </ul> </li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM