fjckls fjckls - 1 month ago 14
CSS Question

Select previous and next sibling of an active element

I want to select one element before and one element after the given class with CSS only. I'm wondering if that's possible ... Here is my list:

<ul>
<li>one</li>
<li>two</li>
<li class='active'>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>


I want to apply some styles to one element before and one after
.active
. I can do it with javascript - no problem, but I was wondering if something like this could be possible:

/* before .active */
ul li.active-element(.active - 1) {
background:red;
}
/* after .active */
ul li.active-element(.active + 1) {
background:blue;
}

Answer

You Can't select previous sibling. But yes you can select next sibling by

ul li.active+ li{
  background:blue;
}

Js fiddle Link

You can select previous sibling by Javascript.