Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
CRISHK Corporation Avatar asked Mar 16 '12 06:03

CRISHK Corporation


People also ask

How do I get next element in CSS?

The element+element selector is used to select an element that is directly after another specific element.

How do I apply CSS to multiple elements?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.

How do I select the next class in CSS?

class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.


2 Answers

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/

like image 83
sandeep Avatar answered Oct 15 '22 09:10

sandeep


It's called sibling selector:

.selected + li {
   color: red;
}

Fiddle here

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

like image 30
Robert Smith Avatar answered Oct 15 '22 10:10

Robert Smith