CSS: apply style only to <a> without internal <img>
I would like to apply a style to the hung links in the list, but only if there is no image inside the <a> element.
The markup is as follows:
<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 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 jsfiddle
+5
3 answers
I doubt it is possible in pure CSS.
However, you can wrap the text in <span> and apply the rules there, i.e. sort of:
<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; } +2
You cannot stylize an element based on its children in CSS, what you can do is assign a special class to the <a> tags that hold the image and do not allow it to be styled:
<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; } +4
add .non-img to li, which without img n do css with .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> 0