I have modified your fiddle and included an additional layer beneath the main container
.container {
position: relative;
display: block;
height: 300px;
width: 300px;
max-height: 300px;
max-width: 300px;
background-color: #000;
border: 2px solid blue;
}
.container2 {
max-width: inherit;
max-height: inherit;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
border: 2px solid green;
}
.container2 img {
max-height: inherit;
max-width: inherit;
}
.cover {
display: none;
}
.container:hover .cover{
display: block;
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background-color: #FFF;
opacity: 0.8;
}
<div class="container">
<div class="container2">
<img src="http://placekitten.com/400/200/">
<div class="cover"></div>
</div>
</div>
<div class="container">
<div class="container2">
<img src="http://placekitten.com/400/800/">
<div class="cover"></div>
</div>
</div>
This setup involves setting a maximum height and width for the container, which is then inherited by the image.
The image adjusts its size accordingly.
Subsequently, the container2 element takes its dimensions from the child elements.
Finally, the cover element utilizes the dimensions of container2.