6

If I wanted to do a CSS selector on a list like this:

<ul>
    <li></li>
    <li><a></a></li>
    <li><a></a></li>
    <li><a></a></li>
</ul>

and I wanted to do a li:hover effect on only the lis that contain an <a> tag, is there a way to specify that in CSS? if li:hover contains <a> then li:hover effect = X?

SharpC
  • 5,368
  • 3
  • 37
  • 36
proseidon
  • 2,005
  • 5
  • 25
  • 53
  • 2
    css doesn't allow you to "reach back" up the cascade chain to change a parent's layout based on a child. – Marc B Jan 24 '13 at 19:56
  • possible duplicate of [Complex CSS selector for parent of active child](http://stackoverflow.com/questions/45004/complex-css-selector-for-parent-of-active-child) – Jan Hudec Jan 25 '13 at 09:36
  • See https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – Ed Randall Apr 17 '17 at 06:02

4 Answers4

5

No, CSS does not allow you to select elements based on their descendants.

Jon
  • 396,160
  • 71
  • 697
  • 768
1

You can do it in JQUERY:

$("a").parent("li").css("color","#923123");

For what you requested, it would be like this:

$("li").mouseover(function(){

   if ($(this).is(':parent'))
   {
       //this <li> has a child, supposed to be <a>
   }

});
Ali Bassam
  • 8,773
  • 20
  • 63
  • 112
0

Depending on your ultimate objective and what the effect is, you could apply the styles to the anchor tag - which then wouldn't apply to those list items without one.

Alternatively, whilst you can't do this directly in CSS, if the list is dynamic and you can identify the list items that contain a link at the point of generation, you could apply classes based on their status and style accordingly.

If it's not a dynamic list, just add the classes manually.

Mark
  • 2,883
  • 1
  • 18
  • 29
  • Okay, thanks. I thought maybe with the new types of CSS selectors there was a way to do this in CSS but I guess I'll have to wait for CSS4 :P – proseidon Jan 24 '13 at 20:02
0

For that you need a CSS4 parent selector, but of course it's not supported for now.

$li:hover a { ... }

If it doesn't matter what tag is inside, you could just use:

li:hover {border:1px solid red}
li:empty:hover {border:0}

:empty selector is not supported in ie7.

http://jsfiddle.net/aD6Ws/

Jquery alternative is :

$("li:has('a')").hover(function() { ... },function(){ ...  })
Jozsef Kerekes
  • 228
  • 3
  • 12