DEV Community

Cover image for CSS: select all siblings using not()
Reuven Hozias
Reuven Hozias

Posted on • Edited on

CSS: select all siblings using not()

Our UX team wanted me to create a navigation menu that dims the rest of the items instead of highlighting the hovered item.

CSS to the rescue!

The solution is quite simple when using the CSS not() pseudo-class:

Image description

The HTML

<div class="menu-items">
  <div>Home</div>
  <div>About</div>
  <div>Contact</div>
  <div>Services</div>
  <div>Blog</div>
  <div>Portfolio</div>
</div>
Enter fullscreen mode Exit fullscreen mode

The SCSS

I've removed the styling properties so we can focus on the actual functionality:

1 .menu-items {    
2     visibility: hidden;
3 
4     & > * {
5         visibility: visible;
6         transition: opacity 500ms;
7     }
8 
9     &:hover > :not(:hover) {
10        opacity: 0.45;
11    }
12 }
Enter fullscreen mode Exit fullscreen mode

We have a container with a .menu-items class.
In line #4, we're selecting all its child elements and adding an opacity animation transition to them.

Line #9 handles the hover effect on elements by setting the opacity of all non-hovered elements using the not() pseudo-class to a lower value.

And what's going on with the visibility property?
We're setting the visibility of the .menu-items container to hidden and then setting the child elements back to visible. This causes the effect to turn off when we hover between the elements.

That's it :)

Top comments (1)

Collapse
 
vodem_descro_d94d13b45e12 profile image
Yasser Latrech

thanks boss