Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: select previous sibling [duplicate]

I've got a list and want to select the previous and next of the one I am hovering

<ul>
    <li>Item1</li>
    <li>Item1</li>
    <li>Item1</li>
    <li>Item1</li>
    <li>Item1</li>
</ul>

I am able to select the next sibling with the "+" selector. But is there a possibility to get the previous?

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

I already tried ul li + li:hover but it doesn't work. Can't belief there is no tricky hack that I could use.

Sure I can do this easily through Javascript but I don't like using JS where I can get the same result with CSS.

like image 522
Hauke Avatar asked Jan 20 '14 14:01

Hauke


People also ask

Can I select a previous sibling CSS?

No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2.

How do I select a previous class in CSS?

Selecting what came before For this use case, we can reverse the order on the HTML, then sort it back in CSS, and use the ~ subsequent sibling combinator or + adjacent sibling selector. This way we'll be selecting the next siblings, but it'll look like we are selecting previous ones.

How do I select my next child in CSS?

The adjacent sibling combinator ( + ) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element .

How do you select all sibling elements in CSS?

CSS All Next Siblings Selector - CSS ~ Sign Selector CSS all next siblings selector matches all element they are siblings of specified element. This Selector identify by ~ (tilde sign) between two selector element. All next siblings selected match all elements whose are sibling of specified element.


1 Answers

There's no way to do this with pure CSS, if you really must select the previous sibling, you're going to have to resort of Javascript or suchlike.

like image 167
arandompenguin Avatar answered Sep 27 '22 01:09

arandompenguin