0

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:

  1. div.grid-container has fixed width and height in pixels to limit overall size of the element.
  2. div.image-container is used for internal purposed (fiters, mirror, javascript behavior).
  3. 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>
cronfy
  • 1,001
  • 1
  • 15
  • 32
  • 2
    % max-height should have a height as reference to work – Temani Afif May 10 '18 at 20:03
  • @TemaniAfif there IS a reference - div.grid-container has height in pixels. The question that "already has an answer" is different, because it that question there are no fixed height container. – cronfy May 10 '18 at 20:11
  • the reference should be the parent element ... the parent of the image should have a height set to allow % of max-height to work ... the logic is the same : max-height/height with % need to have a height defined on parent element, that is the explication in the duplicate question – Temani Afif May 10 '18 at 20:12
  • here is your answer : https://stackoverflow.com/a/14263416/8620333 – Temani Afif May 10 '18 at 20:14

1 Answers1

0

I can’t see your code visually however I believe you’ll need to put a set height on the image. In this instance you could put height: 100%; and width: auto; or width: 100%; height: auto; on the image itself, this will keep the aspect ratio and should reduce the height

EllisJ98
  • 23
  • 5