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.
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With