1

How to get image to fit in div (don't go beyond it) and keep it's aspect ratio while never having more than 150px in height?

<!DOCTYPE html>
<html>
<head>

</head>
<body>

 <div style="border: 1px solid black; height: 200px; width: 200px;">
  <img src="https://about.canva.com/wp-content/uploads/sites/3/2017/02/congratulations_-banner.png" style="max-height: 150px; width: auto;" />
 </div>

</body>

</html>

As you can see here image width is auto and max-height is 150px although this image goes beyond parent div and his borders.

How to make this image keep it's aspect ratio and fit in this div and scale down but also having max-height of 150px. So never height is more than 150px and width is auto to this height to keep it's ascpet ratio and also fit in this div.

Krystian Polska
  • 1,286
  • 3
  • 15
  • 27

2 Answers2

1

As per this answer

you can use

<div style="border: 1px solid black; height: 200px; width: 200px;">
    <img src="https://about.canva.com/wp-content/uploads/sites/3/2017/02/congratulations_-banner.png" style="max-width: 100%;  max-height: 100%;" />
</div>

note:

It would be better to separate CSS from HTML as this answer explains. So instead you should use the code below

#bannerContainer
{
  border: 1px solid black; 
  height: 200px; 
  width: 200px;
}
#banner {
  max-width: 100%;
  max-height: 100%;
}
<div id="bannerContainer">
  <img id="banner" src="https://about.canva.com/wp-content/uploads/sites/3/2017/02/congratulations_-banner.png"  />
</div>
Mathieu VIALES
  • 4,526
  • 3
  • 31
  • 48
1

Give the img max-width:100%.

<!DOCTYPE html>
<html>
<head>

</head>
<body>

 <div style="border: 1px solid black; height: 200px; width: 200px;">
  <img src="https://about.canva.com/wp-content/uploads/sites/3/2017/02/congratulations_-banner.png" style="max-height: 150px; max-width:100%; width: auto;" />
 </div>

</body>

</html>
Tejasvi Karne
  • 628
  • 4
  • 14