Search code examples
htmlcssbrowsercross-browserstylesheet

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


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?


Solution

  • 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/