3

Let's say I have the following <ul>:

<ul>
    <li>Child</li>
    <li><span class="active">Child</span></li>
    <li>Child</li>
</ul>

Is it possible for me to change the style of the <li> via the active <span>?

E.g.:

.active:parent(li) {
    background-color: red;
}

I've been able to achieve this with jQuery, but it flickers on the screen for a split second (waiting for the DOM to load) and I want to avoid that.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
kjdion84
  • 9,552
  • 8
  • 60
  • 87

2 Answers2

4

You can use has():

li:has(> .active) {
    background-color: red;
}

There's no way to do this in CSS.

The best thing to do would be to do something like:

<ul class="has-active">
    <li>Child</li>
    <li><span class="active">Child</span></li>
    <li>Child</li>
</ul>

And style

ul.has-active  {
    ...
}

If you are looking for something that can do parent selectors, then look at something like xpath.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
0

This is impossible with pure CSS because it can't go backwards.

You must use Javascript or jQuery:

$(document).ready(function(){
    $('li').has('.active').css('background-color','yellow');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
    <li>Child</li>
    <li><span class="active">Child</span></li>
    <li>Child</li>
</ul>
Neithan Max
  • 11,004
  • 5
  • 40
  • 58
Ehsan
  • 12,655
  • 3
  • 25
  • 44