htmlcssfilteronhover

Is there a way to make a grayscale filter apply to the rest of the page when hovering over an element?


I am very new to this and am trying to customize my profile on a website that supports html/css coding. I have figured out how to grayscale my images until hover, but I am wondering if there is a way to greyscale the rest of the page on hover so the image is the only colored element.

Everything I have tried has been quite literally just throwing stuff at the wall and seeing if it sticks as I do not know where to even start with something like this, so I don't believe adding my failed attempts will be of any assistance. Below is my current coding for the images, they all fall under the same css ID.

.img{
  filter: Grayscale(100%);
}

.img:hover {
  transform: scale(X);
  filter: drop-shadow(Xpx Xpx  #xxx) !important;
  filter: Grayscale(0%);
}

My apologies if this post does not supply enough information, English is not my first language and I admittedly have no idea what I am doing.


Solution

  • You can achieve something like this by making use of the CSS :has()-selector. Checking the body if it currently has an img that is being hovered. If yes apply the following CSS to all (*) elements that are not an img that is currently being hovered.

    edit: you can exchange img in this selector with any other selector/class, just make sure to replace both.

    edit2: as @CBroe mentioned in the comments, you might want to change the selector to body:has(img:hover) *:not(:hover) (removing the second img selector to make it work when you desired elements are nested.

    body:has(img:hover) *:not(:hover) {
      filter: grayscale(1);
    }
    <img src="https://picsum.photos/id/1/300"/><img src="https://picsum.photos/id/11/300"/><img src="https://picsum.photos/id/21/300"/><img src="https://picsum.photos/id/31/300"/><img src="https://picsum.photos/id/41/300"/><img src="https://picsum.photos/id/51/300"/><img src="https://picsum.photos/id/61/300"/><img src="https://picsum.photos/id/71/300"/><img src="https://picsum.photos/id/81/300"/><img src="https://picsum.photos/id/91/300"/><img src="https://picsum.photos/id/101/300"/>