Apply style to parent if it has child with CSS
HtmlCssHtml 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.