DEV Community

Nic
Nic

Posted on • Originally published at blog.nicm42.me.uk

Styling sibling hover and none hover

I recently had some complicated CSS to get my head around. I have a list of links which I want to style when they’re being hovered/focus on. But, if none of them are being hovered or focused, then I want to style the first one in the list.

The HTML

<ul>
  <li><a href="#">One</a></li>
  <li><a href="#">Two</a></li>
  <li><a href="#">Three</a></li>
  <li><a href="#">Four</a></li>
  <li><a href="#">Five</a></li>
  <li><a href="#">Six</a></li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Styling the hover/focus

This is the simplest part - I am making the background of the links pink when they are hovered or focused.

li a:hover,
li a:focus {
  background-color: pink;
}
Enter fullscreen mode Exit fullscreen mode

Styling the first element

Also, simple.

li:first-of-type a {
  background-color: pink;
}
Enter fullscreen mode Exit fullscreen mode

Styling the siblings

If we just make the hover/focus pink and the first element pink when we aren’t hovering/focusing then the first element is pink which is what we want. But then it keeps being pink even when we’re hovering/focusing on something else. What we need to do is to unstyle the siblings when one is being hovered/focused.

li:has(~ li a:hover) a,
li:has(~ li a:focus) a {
  background-color: unset;
}
Enter fullscreen mode Exit fullscreen mode

This is saying that if an li has a sibling with an a that is being hovered/focused, then style this a.

Downside

There is a downside to this. If you hover over an element, come off it so you’re not hovering on anything, then hover on another element shortly after, then the background jumps to the first one in between, which looks a bit odd.

Final code

Here is the whole code:

Top comments (0)