DEV Community

Francesco Vetere
Francesco Vetere

Posted on • Edited on

CSS-only direction-aware hover effects

Hi everyone! πŸ‘‹ I just discovered a really great way to build a simple direction-aware hover mechanism using nothing but CSS (big thanks to Kevin Powell 😁), and I wanted to share it with you with this simple codepen I created.

If you hover over any of these links with your mouse coming from the top or the bottom, you'll notice a simple decoration coming under the link itself: nothing too fancy, plain old CSS here.

The real magic comes if you do hover on a link coming from its left or its right: in these cases, you'll notice that this decoration doesn't just "appear" under the link, it slides into it!

This cool effect is only possible thanks to the :has() selector: in this particular example, it basically allows us to target an <li> element such that its next sibling is currently hovered.

The :has() selector is kinda new in the CSS world, so it is possible that your browser currently doesn't support it (you can check that here).
If that's the case, you just won't see this nice sliding effect, but the overall layout won't break. So, I consider this a really good progressive enhancement.

Without :has(), this operation would have required some JavaScript in order to manually target the <li> that meets the desired condition. Now instead, this is possible using nothing but CSS: kinda amazing in my opinion! 😁

Buy Me A Coffee

Top comments (0)