7

I would like to apply style to hovered links in a list, but only if there is not image inside <a> element.

The markup is like this:

<div id="leftcolumn">
  <ul>
    <li><a href="http://google.com">google</a></li>
    <li><a href="http://google.com"><img src="http://cso.cz/wpimages/cz2.gif"></a></li>
  </ul>
</div>

and my css:

div#leftcolumn ul a:hover{ 
  background-color: #F8F8F8; 
  color: Black; 
  border-bottom: 1px solid Black; 
}

I have tried this css, but to no avail:

div#leftcolumn ul a:hover < img{ 
  background-color: #F8F8F8; 
  color: Black; 
  border-bottom: 1px solid Black; 
}

Here is the jsfiddle

Zbynek
  • 5,673
  • 6
  • 30
  • 52

3 Answers3

5

You cannot style an element based on it's children in CSS, what you can do is assign a special class for <a> tags that hold the image and prevent styling it:

<div id="leftcolumn">
      <ul>
        <li><a href="http://google.com">google</a></li>
        <li><a href="http://google.com" class="withImage"><img src="http://cso.cz/wpimages/cz2.gif"></a></li>
      </ul>
</div>

div#leftcolumn ul a:not(.withImage):hover{ 
  background-color: #F8F8F8; 
  color: Black; 
  border-bottom: 1px solid Black; 
  border-top: 1px solid black; 
} 
KAD
  • 10,972
  • 4
  • 31
  • 73
  • if you are going to put a class on the anchor, why not just put it on the one with text and target that rather than on the one with the image and targetting not that? – Pete Jan 05 '16 at 09:12
2

I doubt this is possible in pure CSS.

However, you could wrap text in a <span> and only apply rules there, i.e. something like:

<div id="leftcolumn">
  <ul>
    <li><a href="http://google.com"><span>google</span></a></li>
    <li><a href="http://google.com"><img src="http://cso.cz/wpimages/cz2.gif"></a></li>
  </ul>
</div>

CSS:

div#leftcolumn ul a:hover > span { 
  background-color: #F8F8F8; 
  color: Black; 
  border-bottom: 1px solid Black; 
}

Updated JSFiddle

Cedric Reichenbach
  • 8,970
  • 6
  • 54
  • 89
0

add .non-img to li which is without img n do css with using .non-img

div#leftcolumn ul li.non-img a:hover{ 
  background-color: #F8F8F8; 
  color: Black; 
  border-bottom: 1px solid Black; 
  border-top: 1px solid black; 
}
<div id="leftcolumn">
      <ul>
        <li class="non-img"><a href="http://google.com">google</a></li>
        <li><a href="http://google.com"><img src="http://cso.cz/wpimages/cz2.gif"></a></li>
      </ul>
</div>
Sagar Kodte
  • 3,723
  • 4
  • 23
  • 52