I am trying to set max-height: 100%
for image, that is inside several nested containers. One of image's parents has height in pixels. But image still exceeds parent's height.
Nested containers are required for different purposes:
- div.grid-container has fixed width and height in pixels to limit overall size of the element.
- div.image-container is used for internal purposed (fiters, mirror, javascript behavior).
img
itself just must not exceed overall size.
I thought that if one of parents has fixed height, then setting max-height
to any internal element will limit it's height to parent's height. Unfortunately this did not work (see the snippet).
I know that I can set image's max-height
in pixels (200px, as grid-container height), but this widget is designed for using in different places, so I do not know it's container exact height beforehand, I only know it's fixed.
How do I make the image not to exceed container's height without using javascript, with CSS only?
/* page grid element- has fixed height and width */
.grid-container {
width: 200px;
height: 200px;
background-color: green;
}
/* Image container - required for some purposes, must not exceed container size */
.image-container {
outline: 5px solid red;
max-width: 100%;
max-height: 100%;
}
/* image must not exceed it's container */
img {
max-width: 100%;
max-height: 100%;
display: block;
}
<h2>does not work - image height exceeds container's height</h2>
<div class="grid-container">
<div class="image-container">
<img src="http://via.placeholder.com/150x300">
</div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<h2>for width it works as expected</h2>
<div class="grid-container">
<div class="image-container">
<img src="http://via.placeholder.com/300x150">
</div>
</div>