5

I have a list with an item which, when hovered over, should highlight. I've got this working fine as below:

li.test:hover
{
   text-decoration: underline
}

However, this list item contains another list, and using the above CSS rule all list items in the child list become underlined as well. I'd like only the first li (the one which is actually hovered over) to underline. I did try to use child selectors but I didn't find anything that worked (though it's probably really obvious).

How can I apply a style only to the current element and not its children?

Jsfiddle: http://jsfiddle.net/Mansfield/2CtFW/

Mansfield
  • 14,445
  • 18
  • 76
  • 112
  • 4
    The problem has nothing to do with the selector but with how `text-decoration` works. See http://stackoverflow.com/q/1823341/218196. It cannot be fixed by using a more specific selector alone. – Felix Kling Apr 15 '13 at 18:39
  • @FelixKling Interesting. Thanks for the info! – Mansfield Apr 15 '13 at 18:44
  • @Juan: It can't be done. The effect applies to all text of the element and descendants cannot remove that effect, just like the accepted answer in the linked question says. Maybe it will be changed one day, but for now it looks like we have to change the markup. – Felix Kling Apr 15 '13 at 18:58
  • @FelixKling It could be done if the following selector worked `li:hover li {text-decoration:none}` which would undo the effect from the parent li – Ruan Mendes Apr 15 '13 at 19:01
  • @Juan: Yes of course. But that's not how `text-decoration` works as per specification. – Felix Kling Apr 15 '13 at 19:31

1 Answers1

3

You can cheat it but wrapping your text content into some other node which doesn't wrap its children http://jsfiddle.net/2CtFW/7/

This avoids the cascading rules since the inner lists aren't contained by the element that is receiving the text-decoration rule. Initially, I thought this was a hack, but considering the fact that you can't style text elements and this is really what you want to do in this case, I think this is the only way to achieve what you want.

<ul>
    <li>
        <span>Item1</span>
        <ul>
            <li><span>Item2</span></li>
        </ul>
    </li>
<ul>


li>span:hover
{
    text-decoration: underline
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217