CSS max-height and max-width property; parent size defined in % of window size

Viewed 618

For my page layout I wanted to define a .parent element size relative to the window size:

.parent {
  position: relative;
  height: 100%;
  width: 75%;
  top: 0;
  left: 12.5%;
}

Inside this .parent, I want to display an image .child element that should be rescaled to the size of of .parent (the aspect ratio of the image fits that of .parent, so this won't be a problem):

.child {
  position: absolute;
  max-height: 100%;
  max-width: 100%;
  top: 0;
  left: 0;
}

HTML

<div class="parent">
   <img class="child" src="/images/some_image.jpg">
   <img class="child" src="/images/another_image.jpg">
</div>

However, this does not seem to work as the image is not displayed at all.

I found that the computation of the height for max height can run into problems sometimes, which would result in the element not getting displayed. This seems to be the case here. Changing either the height / width of .parent or the max-height / max-width of .child to an absolute value (e.g. 500px) gets the image displayed, but this will not work with windows of different sizes (like with different screen resolutions).

How can I work around this problem? Thank you very much in advance!

2 Answers

Try using vh and vw for the parent. Also, define the child's height and width instead of max-height and max-width:

.parent {
  position: relative;
  height: 100vh;
  width: 75vw;
  top: 0;
  left: 12.5%;
}

.child {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
}
<div class="parent">
   <img class="child" src="/images/some_image.jpg">
   <img class="child" src="/images/another_image.jpg">
</div>

Read more about css units here.

Use vh (viewport height) and vw (viewport width) units for sizing relative to the window.

.parent {
  position: relative;
  height: 100vh;
  width: 75vw;
  top: 0;
  left: 12.5vw;
}

.child {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background: red;
}
<div class="parent">
  <img class="child">
  <img class="child">
</div>

Related