Last Updated: February 25, 2016
·
9.491K
· mwielbut

Create a list hover effect to highlight elements using pure CSS

Everyone has used CSS pseudo elements to create custom link hover effects :hover</code> or attach an icon or text to an element using :before</code> or :after</code> but the fun really starts when you start using multiple pseudo elements in combination.

Take, for example, a situation where you want to highlight an element in a list:

  • Entry a
  • Entry b
  • Entry c
  • Entry d

In the normal state you want all elements visible - meaning opacity: 1.0;</code>. When your mouse hovers over one of the elements in the list, however, you'd like all the other elements to fade away - emphasis should be placed on the highlighted element.

In the past, one would accomplish this with some javascript. Fire off events each time an entry is hovered. Any element that's not hovered would fade away, the hovered element would fade in.
Alternatively, you could do some clever hit-tests - if the cursor is hovering over the list, fade out all elements that fail the hit-test.

Now, enter pure CSS:

ul > li {
    opacity: 1.0;
}

ul:hover > li:not(:hover) {
    opacity: 0.5;
}

What's going on here?

In our first statement, we're ensuring that all elements, in their normal state are faded-in..
OK, not much so far. But now the twist...
In our second statement we state that if the user hovers over the list, select all elements not being hovered over and fade them out.

When the list loads all elements are faded-in. When the user hovers over the list, all elements fade away. When the user hovers over an element, it fades in. When the user hovers off the list, all elements fade back in. A nice simple visual effect made possible by combining 3 powerful CSS pseudo tags and 3 lines of code.

Of course, here's the fiddle:
http://jsfiddle.net/3hz4d/