Apply style to parent if it has child with CSS

HtmlCss

Html Problem Overview


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

Html Solutions


Solution 1 - Html

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGreen WizardView Question on Stackoverflow
Solution 1 - HtmlMildlySeriousView Answer on Stackoverflow