Unfortunately, CSS has no such thing like “previous” selector. That means you are not able to select element or elements which appear in HTML code before your particular element. Why? CSS stands for Cascading Style Sheets and cascade is like waterfall, it goes from top to down. There is no backward motion.

All we can do is to match next closest sibling (operator +) or match all following siblings (operator ~).

Ok, but technology is moving forward very fast and really, there is no solution? No, there is no official solution still. But we can simulate our well-known sibling and general sibling selectors to match previous elements.

Use cases

For now, let’s ask a question: What would we need previous selectors for? When could we use them?

I think the most common use case is “stars rating”. When user hovers over one star, we would like to make it activate all preceding stars.

Stars rating example

Of course you can find tons of other use cases, it depends on your needs and imagination.

Solutions

As far as I know the most common solution is to use CSS property direction: rtl. It’s explained very well in this article.

But I would like to present totally different approach. It’s based on flexbox and its order property. We have to change visual order of elements. You can do it by setting order of each element manually:

.element-1 {
  order: 3;
}
.element-2 {
  order: 2;
}
.element-3 {
  order: 1;
}
// and so on...

…but I don’t think it’s a good idea. It produces a lot of code which basically does the same thing.
You can achive the same by using flex-direction: row|column-reverse.

reverse word is crucial here. You do not depend on number of elements anymore and you can be sure that all of elements will be in reversed order.

Explanation

Below you can find an example with star rating based on flexbox. Feel free to play with it:

So basically you can catch the next element with + selector and then change visual order with flex-direction: row|column -reverse.

I would also like to show you an example with a checkbox and a label. It consists of just small piece of code showing how to change checkbox into toggle slider, using just CSS, without additional div's. It works on all major browsers.

Accessibility

Above-mentioned solution changes only the visual order but does not change real order in HTML code, so there is no possibility to set focus on proper element. Focus will be applied from the last visible element to the first one. So if you’re working on page which requires high accessibility you should keep it in mind.

Go ahead and try to mess around with codepen below.

hint: Click on star and then use the tab key :)

I hope you enjoy that solution, and if you know some other neat tricks how to achive similiar thing, let me know leaving a comment below.