Stephen
Stephen

Reputation: 3992

What's the best way to enlarge the height of image to max-height?

I have a container to display image, the container has a fixed 100% width. My requirements are:

In my example, the first two images display correct. However, the third image is wrong, because the width is not reach 100% or the height is not reach the max height.

How can I fix this issue?

.container {
  border: 1px solid black;
  height: 200px;
  width: 100%;
}

img {
  max-width: 100%;
  max-height: 200px;
  width: auto;
  display: block;
  margin: auto;
}
<div class="container">
  <img src="https://i.sstatic.net/kZPXw.png" />
</div>

<div class="container">
  <img src="https://i.sstatic.net/IfTIL.png" />
</div>

<div class="container">
  <img src="https://www.gravatar.com/avatar/62345e20906dbccbf7e18f11ab4bd047?s=64&d=identicon&r=PG&f=1" />
</div>

You can play here as well: https://jsfiddle.net/d425c1bh/2/

Upvotes: 0

Views: 72

Answers (1)

Rhiana Heath
Rhiana Heath

Reputation: 26

Try this, adding object-fit and replacing the width auto with width 100%

.container {
  border: 1px solid black;
  height: 200px;
  width: 100%;
}

img {
  max-height: 200px;
  width: 100%;
  max-width: 100%;
  object-fit: contain;
  display: block;
  margin: auto;
}

see it working here

Upvotes: 1

Related Questions