Smarticles101
Smarticles101

Reputation: 1926

Image resize, conform to max-width but change height to maintain aspect ratio

I've been looking for an answer to this. I'd prefer a solution with just CSS, but I've been unable to find one.

I've got a popup of a fixed width, and it will grow in height if the contents are larger. Inside, I put an image which should take half of the popup while maintaining aspect ratio and being as large as possible without going off the screen, and a div to hold information about the image, which should also be half the screen, so that the image and div are side-by-side. Example here: https://codepen.io/Smarticles101/pen/WdmZLx

I can set a height on the image of 90vh to make it larger and a max-width of 50% to make sure it only takes half of the popup. However, if the window shrinks in width or if I make the fixed width of the popup smaller, the image will maintain height and max-width, thus not maintaining aspect ratio.

How can I make the image maintain aspect ratio while it shrinks in width?

Html:

<div id="popup">
  <img src="https://images.freeimages.com/images/large-previews/12d/frangipani-02-1311438.jpg" alt="image" />
  <div id="sidedata">
    <h1>Image</h1>
    <p>Some data about the image here</p>

  </div>
</div>
<br />
<div id="popup">
  <img src="https://www.w3schools.com/images/w3schools_green.jpg" />

</div>

CSS:

#popup {
  max-width: 50%;
  background-color: blue;
}

img {
  height: 90vh;

  max-width: 50%;
  /*
    The image will not maintain aspect ratio if the max-width is reached, it will maintain height as whatever it was set to originally rather than     shrink in height.
  */

  display: inline-block;
}

#sidedata {
  max-width: 50%;
  display: inline-block;
}

Upvotes: 0

Views: 202

Answers (1)

Ceci Semble Absurde.
Ceci Semble Absurde.

Reputation: 530

short anwser, hope that will help, try with max-height :

img {
  max-height: 90vh;
  max-width: 50%;
  display: inline-block;
}

Upvotes: 0

Related Questions