128

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

tanguy_k
  • 10,220
  • 6
  • 49
  • 54
Green Wizard
  • 3,219
  • 4
  • 16
  • 29
  • 4
    You can't. Bash the spec makers. – bjb568 Jan 21 '14 at 08:16
  • 2
    See http://stackoverflow.com/questions/45004/complex-css-selector-for-parent-of-active-child or http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – Jan Johansen Jan 21 '14 at 08:18
  • It's not possible, use the jquery. – Nikola Nikolić Jan 21 '14 at 08:18
  • 3
    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. – user3094755 Feb 08 '16 at 17:56

1 Answers1

89

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.

Tanasos
  • 3,681
  • 3
  • 30
  • 58
MildlySerious
  • 8,112
  • 2
  • 27
  • 29