According to the given details, this should be enough:
.parent {
height: 300px;
width: 300px;
border: 1px solid black;
}
.parent img {
height: 25%;
width: auto;
}
<div class="parent">
<img src="https://visualhunt.com/photos/2/cat-feline-cute-domestic-young-looking-curious.jpg?s=s" />
</div>
Although, I should mention a few CSS limitations:
- CSS relative height and width (%) can only be taken from a definitive value. meaning that only if the parent has a not relative height, can the children be set to relative height, and same goes for width.
- Image resizing is not recommended, thus it’s enough to set one of the attributes and let the other
auto
matically fix it’s ratio.
An easy way of seeing it would be to take this snippet and change the parent’s height values to different things, and see how the image is affected.
If the height of the parent is not definitive through CSS, you can “hack” this feature using DOM.
setTimeout(() => {
let parent = document.getElementById('parent');
let image = document.querySelector('#parent img');
let parentHeight = parent.offsetHeight;
image.style.height = (parentHeight / 4) + 'px';
}, 2000);
#parent {
height: 50%;
width: 50%;
}
#parent img {
height: 25%;
width: auto;
}
<div id="parent">
<img src="https://visualhunt.com/photos/2/cat-feline-cute-domestic-young-looking-curious.jpg?s=s" />
</div>
I wouldn’t call it a perfect example because honestly it was tough simulating an unknown height container in this snippet feature – but I made it delayed in 2 seconds for the example to be visual.