how to apply css rule to the previous and the next element in HTML?

CRISHK Corporation picture CRISHK Corporation · Mar 16, 2012 · Viewed 44.7k times · Source

For example:

You have this:

<ul>
 <li>zero</li>
 <li>one</li>
 <li class="selected">two</li>
 <li>three</li>
 <li>more elements</li>
</ul>

CSS:

.selected:previous {
   color: red;
}

.selected:next {
   color: green;
}

That's possible?

Answer

sandeep picture sandeep · Mar 16, 2012

It's not possible with pure css. You can style next but not previous element.

But you can do a trick with css. Instead of give class selected you can give class to your previous element. Like this:

HTML

<ul>
 <li>zero</li>
 <li class="previous">one</li>
 <li>two</li>
 <li>three</li>
 <li>more elements</li>
</ul>

CSS

.previous{
   color: green;
}
.previous + li{
   color: red;
}
.previous + li + li{
    color:yellow;
}

Check this http://jsfiddle.net/S5kUM/2/