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.

Temani Afif
  • 211,628
  • 17
  • 234
  • 311
kjdion84
  • 8,439
  • 6
  • 53
  • 81

2 Answers2

4

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.

dwjohnston
  • 9,419
  • 24
  • 94
  • 167
1

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
  • 9,375
  • 4
  • 34
  • 56
Ehsan
  • 12,231
  • 3
  • 23
  • 42