0

I want to highlight an image when a user hovers over it.

To do that, I'd like to put an overlay over everything else (or honestly, I'd be happy putting an overlay over everything including the image, and then putting something to brighten the image as well).

Is there anyway to do this without JS? I'm happy to use a JS solution if that's all that's available, but I was wondering if there was any CSS-only trickery that could manage to do this.

Example HTML would be like this:

<body>
<div>
<Other Elements />
<img src="...." />
</div>
</body>

Preferably everything would be darkened except the <img> tag.

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232
  • 1
    Pretty sure this is not what I want. I don't want to overlay an image over another image. I want to darken the rest of the screen when hovering over a div or img. – Steven Matthews Nov 29 '17 at 00:45

1 Answers1

1

You could use a sibling selector: .container img:hover ~ .overlay { background-color: rgba(0,0,0,0.8); }

body {

}

.container {
  position: relative;
  text-align: center;
  margin: 10px auto 0;
  padding-bottom: 10px;
}

.container .other {
  display: inline-block;
  margin: 20px 10px 10px;
  width: 100px;
  height: 100px;
  background-color: darkorange;
  z-index:1;
}


.container img {
  display: inline-block;
  margin: 10px 10px 10px;
  z-index:1;
  position: relative;
  transition: all 300ms ease;
}

.overlay {
  background-color: rgba(0,0,0,0);
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  pointer-events: none;
  z-index:1;
  transition: all 300ms ease;
}

.container img:hover ~ .overlay {
 background-color: rgba(0,0,0,0.8);
}

.container img:hover {
 z-index: 2;
 transform: scale(1.1);
 cursor: pointer;
}
<body>
  <div class="container">
    <div class="other"></div>
    <div class="other"></div>
    <img src="https://picsum.photos/100/100?image=2" />
    <div class="other"></div>
    <img src="https://picsum.photos/100/100?image=4" />
    <div class="other"></div>
    <img src="https://picsum.photos/100/100?image=6" />
    <img src="https://picsum.photos/100/100?image=8" />
    <div class="overlay"></div>
  </div>
</body>
Daniel Sixl
  • 2,488
  • 2
  • 16
  • 29
  • Hrm, so that would work with my simplified example, but would it work with a nested image? I've got the image inside at least half a dozen divs. – Steven Matthews Nov 29 '17 at 01:54
  • It would work with a sibling, hence the sibling selector - targeting the elements in the tree being a sibling of the overlay. `.container .yourSiblingsOfOverlay:hover ~ .overlay { background-color: rgba(0,0,0,0.8); }` Then target nested images of those siblings: `.container .yourSiblingsOfOverlay:hover img { z-index: 2; transform: scale(1.1); cursor: pointer; }` – Daniel Sixl Nov 29 '17 at 13:20