'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?



Solution 1:[1]

To achieve this in my website project for Uni, I did this;

.container:hover img {
      transform: scale(1.02);
      transform-duration: 0.1s;
      transition-timing-function: linear;
    }

.container:not(:hover) img {
      transform-duration: 0.1s;
      transition-timing-function: linear;
    }

You will want to use the transform property over the changing the height or width itself as transform allows you to do different things with the sizing, e.g. adding transitions.

The first CSS styling, .container:hover img, scales up the image. The transform: scale() determines how big the image becomes when you hover over it (You can change this to what you want, 1.02 is what I have used in mine). The transform-duration is how long it takes to transition to the new size. The transition-timing-function determines the speed curve of the transition. A linear curve will scale it at the same speed. See this W3Schools article on the different curve speeds

The second CSS styling, .container:not(:hover), scales the image down to its original size using the same techniques as previously used. :not(:hover) essentially tells the property "if the mouse moves off of this container, do this"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1