tired63194
tired63194

Reputation: 23

Expand image only when hovering over containing div

Assuming I have HTML with the structure <div><img></div>, then expanding that image on hover is simple enough by adding some CSS like this.

div:hover img {
  height: /* something */;
}

But if the expanded image exceeds the size of the div it's contained in, once you've hovered over the div, the image stays expanded for as long as the mouse remains over the expanded image, not the div itself, as you can see in the demo below.

.container {
  height: 200px;
  width: 200px;
  border: 3px solid red;
  text-align: center;
}

.container:hover img {
  height: 300px;
}
<div class="container">
  <img class="image" src="https://via.placeholder.com/300.png" height="200px">
</div>

What I would like to accomplish, is for the image to only stay expanded while the mouse is hovering over the 200px x 200px area of the .container div, and shrink back to its original size when the mouse leaves that area.

Is there a way to accomplish this with CSS?

Upvotes: 0

Views: 895

Answers (1)

A Haworth
A Haworth

Reputation: 36567

If you remove the pointer events on the img then hovering over the expanded image will have no effect, but the hover will be picked up by the underlying container.

.container {
  height: 200px;
  width: 200px;
  border: 3px solid red;
  text-align: center;
}

.container:hover img {
  height: 300px;
}
img {
  pointer-events: none;
}
<div class="container">
  <img class="image" src="https://via.placeholder.com/300.png" height="200px">
</div>

Upvotes: 1

Related Questions