17

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?

CRISHK Corporation
  • 2,948
  • 6
  • 37
  • 52
  • 1
    Don't think a CSS only solution is available but a *pure* JavaScript option would be: http://stackoverflow.com/questions/574904/get-next-previous-element-using-javascript – Greg Mar 16 '12 at 08:30
  • possible duplicate: http://stackoverflow.com/q/1817792/3597276 – Michael Benjamin Mar 13 '16 at 00:17

4 Answers4

24

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/

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
sandeep
  • 91,313
  • 23
  • 137
  • 155
6

It's called sibling selector:

.selected + li {
   color: red;
}

Fiddle here

However, there is no sibling selector for the previous element. ​

r_31415
  • 8,752
  • 17
  • 74
  • 121
2

This would have to be done with JavaScript.

If you are using jQuery, it can be done like this:

$('.selected').prev().css('color', 'red');
$('.selected').next().css('color', 'green');
Colin Kenney
  • 597
  • 5
  • 10
1

You can use display: flex; and flex-direction: row-reverse; to reverse the list.

http://codepen.io/bscherer/pen/XMgpbb