Apply style to parent if it has child with css

I am trying to apply styles to parent if it has child elements.

So far, I have applied styles to child elements, if any. But I want a style parent if parent has a child using ONLY CSS .

follows html

 <ul class="main"> <li>aaaa</li> <li>aaaa</li> <li>aaaa</li> <li>aaaa</li> <li>aaaa <ul class="sub"> <li>bbbb</li> <li>bbbb <ul> <li>cccc</li> <li>cccc</li> <li>cccc</li> </ul> </li> <li>bbbb</li> <li>bbbb</li> <li>bbbb</li> </ul> </li> <li>aaaa</li> <li>aaaa</li> <li>aaaa</li> </ul> 

CSS code

 * { margin:0; padding:0; text-decoration:none; } .main li { display:inline-block; background:yellow; color:green; } .main > li > ul > li { background:orange } .main > li > ul > li > ul >li { background:pink; } 

FIDDLE works

+48
html css html5 css3
Jan 21 '14 at 8:14
source share
1 answer

This is not possible with CSS3. There is a suggested CSS4 selector, $ , to do just that, which might look like this (selecting the li element):

 ul $li ul.sub { ... } 

See a list of CSS4 selectors here .

Alternatively, with jQuery, a single layer that you could use would be the following:

 $('ul li:has(ul.sub)').addClass('has_sub'); 

Then you can continue and style li.has_sub in your CSS.

+45
Jan 21 '14 at 8:41
source share



All Articles