Here's a tough one. Let's say I have the following markup:

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

Let's also say I'm applying styles to whichever list item is currently being :hovered over, like so:

ul li:hover { color: red; }

I know I can also apply styles to whichever element immediately follows that :hovered list item by using the adjacent sibling selector (lets say we want the list item to be blue):

ul li:hover + li { color: blue; }

How do I select the element that immediately PRECEDES the :hovered element? This would kind of be a reverse adjacent selector. I would love to see syntax look sort of like ul li:hover - li, but I realize that won't work. I've done a ton of googling that all suggests that this is not possible but I remain hopeful - there must be a way!

Thanks, Brad.

4 answers

1
point
This was chosen as the best answer

good ol jQuery seems like the only viable answer in this case.

$('ul li:hover').prev(); //this should do the trick.
Answered about 6 years ago by Jeffrey Nolte
0
points

Yes, I've seen the jQuery method but I'm really looking for a CSS-only solution. Even if it was some kind of illusion where it appeared to be doing what I've described but in fact it would select more than the previous element if you simply added more list items.

I've been playing with the :nth-of-type pseudoclass but so far have had no luck. I've also read a bit about the negation pseudoclass (:not) but am not yet sure how it could apply here.

Thanks, Brad.

Answered about 6 years ago by Brad Marshall
0
points

Unfortunately I'd have to say Jeffrey's is the best answer based on simplicity and cross-browser compatibility.

Whilst I understand you might have to find a non-js solution, there's no CSS2 that does this and certainly no well-supported CSS3 that does either. Unless is has to be a non-JS I'd put my faith in jQuery and save yourself a lot of head-scratching.

Answered about 6 years ago by John Catterfeld
0
points

Okay, well I'll concede - this is actually for a CSS-only demo but if one is able to use javascript, jQuery's prev() method definitely looks like the quickest path to a solution. Thanks for the help guys!

Brad.

Answered about 6 years ago by Brad Marshall