DEV Community

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

Posted on • Edited on

5 1 1

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 :)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
vodem_descro_d94d13b45e12 profile image
Yasser Latrech

thanks boss

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay