163

I'm trying to apply styles to the parent if it has child elements.

So far, I've applied styles to the child elements if present. But I want to style the parent if the parent has child, using ONLY CSS.

following is the 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> 

the 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; } 

working FIDDLE

4
  • 5
    You can't. Bash the spec makers. Commented Jan 21, 2014 at 8:16
  • 2
    See stackoverflow.com/questions/45004/… or stackoverflow.com/questions/1014861/… Commented Jan 21, 2014 at 8:18
  • It's not possible, use the jquery. Commented Jan 21, 2014 at 8:18
  • 4
    Unfortunately I can only answer this question in a comment, but there is a CSS Selector for :empty so If you style the element for with children and then style for when no children with :empty you should achieve the effect you want. Commented Feb 8, 2016 at 17:56

1 Answer 1

144

You can use has():

ul li:has(ul.sub) { ... } 

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... } 

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

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

You could then go ahead and style the li.has_sub in your CSS.

Sign up to request clarification or add additional context in comments.

9 Comments

According to this similar question: stackoverflow.com/questions/1014861/… the :has() pseudoclass no longer works with any browser as of 2016. Just so people don't get frustrated at this not working.
:has() should be the proposed CSS4 selector instead of the more obscure $ one ...
$ now replaced with ! appended to a selector. Look here for more info: w3.org/TR/selectors4/#subject
@NicolaeSurdu you are right, w3 is so backwards
According to the Feb 2018 working draft, ! has been replaced with :has()
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.