Fun with CSS Sibling Selectors

Sibling selectors are super helpful for applying different styles to neighboring elements in a list. And they can produce some pretty nifty effects when combined with transforms and transitions. Let's go over sibling selectors and look at an example of when to use them.

CSS gives us two selectors that we can use to target neighboring elements of the same parent: the adjacent selector, and the general sibling selector.

The adjacent selector ul li:hover + li{...} will grab the first item immediately to the right.
adjacent selector

The general sibling selector ul li:hover ~ li{...} will grab all of the items to the right.
general selector

The slight caveat bummer is that CSS doesn’t give us a “before” selector, so we can't directly target the elements to the left. But we can work around this by first applying styles to all child elements, and then overriding the styles of the elements to the right.

Let's look at what we can do with this exciting new information. Check out my example on Codepen

princess-bubblegum

When a user hovers over Princess Bubblegum, we want the other characters in the list to rotate to face her. Likewise with Jake, Finn, and so on. That means we’ll need to apply a different rotation value depending on if an element is to the left or right of the hovering element. We can do this with pure CSS by using our sibling selectors.

Since CSS doesn’t have a “before” sibling selector, we’ll need to apply a rotation to all of the elements in the list first. This will ensure we catch those elements to the left.

.adventure-list:hover li {
   transform: rotateY(30deg);
} 

Next we need to set the rotation of the elements on the right. To do that, let's use the (~) combinator general sibling selector, and select everything on the right of our hovering list element. Now we can set the rotation in the opposite direction.

.adventure-list  li:hover ~li{
   transform: rotateY(-30deg);
}

Double KO! Awww yiss

knockout

The last thing we need to do is select the hovering element and reset its rotation back to zero.

.adventure-list li:hover{
   transform: rotateY(0deg);
}

I’ve changed the background between states so we can take a peek at how this works. Elements to the left are yellow, elements to the right are blue, and the selected element is white.

Oh snap, it works!
highfive

Sibling selectors are really neat and powerful for creating interactive menu effects.

Check out my live example or on codepen

Thanks for following along, have fun, and rock on!