简体   繁体   中英

Using CSS, how do I change the font color of parent <li> tag if child <li> tag is hovered over

HTML:

<ul>
<li>LINK 1</li>
<li>LINK 2</li>
<li>LINK 3
   <ul>
   <li>link 3.1</li>
   <li>link 3.2</li>
   </ul>
</li>
</ul>

How would I modify this in CSS to where if link 3.1 or 3.2 are hovered over, it will change the text color for LINK 3 (the parent link).

I hope I made this simple enough and asked in the best way possible. I know how to change the text color of each thing independently, just don't know how to change the text color of the parent li tag.

Unfortunately, currently it isn't possible to select the parent of an element with CSS, which is what you'll ultimately need to do. You will need to resort to javascript for that.

See this very similar (in scope) question and for quick solutions achieved with jQuery: Is there a CSS parent selector?

if i understand your question right: you can target the parent li and then override the children's color.

<ul>
<li>LINK 1</li>
<li>LINK 2</li>
<li>LINK 3
   <ul>
   <li>link 3.1</li>
   <li>link 3.2</li>
   </ul>
</li>
</ul>

li:hover{
    color:blue;

}

li > ul > li{
    color: black;
}

here's a jsfiddle: http://jsfiddle.net/eedWZ/1/

if you need different sub li's to trigger different colors on the parent, that is impossible via css as far as i know, but could be done easily with javascript. let me know if that was your intention and i can help with the javscript for that.

After playing with code a little, I was able to finally find the solution I was looking for. I am pasting the solution below in code and a link to JS fiddle.

HTML

<ul>
<li>LINK 1</li>
<li>LINK 2</li>
<li>LINK 3
   <ul>
   <li>link 3.1</li>
   <li>link 3.2</li>
   </ul>
</li>
</ul>

CSS:

li:hover { color: red; }
li:hover li { color: black; }
li li:hover { color: red; }

JS Fiddle: http://jsfiddle.net/Nz5Gq/1/

li:hover
{
color:blue;
cursor:pointer;
}
li:hover li
{
color:Red;
}
li ul li:hover
{
color:Red;
cursor:pointer;
}

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