
Css 4 min read
CSS Trick: Selecting and Changing Sibling Elements on Hover
You can style the elements before and after the one being hovered without a single line of JavaScript - :has() plus the general sibling combinator is all it takes.
- css
- selectors
- frontend
Have you ever wondered how to select and change the styles of previous and next sibling elements when one of the elements is being hovered? While using JavaScript is certainly an option, did you know that you can achieve the same effect using pure CSS?
Consider that we have the following elements:
<div>
<a>1</a><a>2</a><a>3</a><a>4</a><a>5</a>
</div>And the CSS rule is:
a { color: #f55; }Now, here comes the interesting part. I use the :has() selector along with the general sibling combinator ~ to target the previous sibling elements - the ones before a:hover - and I use ~ a to select the next sibling elements when any of the <a> elements is being hovered. This combination of selectors lets us precisely select and style the desired elements based on the hover state.
a:has(~ a:hover),
a:hover ~ a {
color: #000;
}