Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: apply style only on <a> without inner <img>

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

like image 755
Zbynek Avatar asked Jan 05 '16 09:01

Zbynek


2 Answers

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; 
} 
like image 99
KAD Avatar answered Sep 18 '22 18:09

KAD


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

like image 34
Cedric Reichenbach Avatar answered Sep 17 '22 18:09

Cedric Reichenbach