Kacy
Kacy

Reputation: 3430

Make img grow to max width/height regardless of container and maintain aspect ratio

I have an <img> which is positioned absolutely within a <div>. The <div> is 100px by 100px. The <img>, when clicked, should grow to a known max width or height, say 500px by 700px. If the <img> is smaller, say 300px by 250px, then that's as large as it should get. Aspect ratio should be maintained.

Setting height and width to 100% just makes the <img> the size of the containing <div>.

I'm looking for either a css or vanilla javascript solution. (I don't require the code for a click animation, just a static end result so I can apply the concept)

Upvotes: 0

Views: 1041

Answers (1)

David Chelliah
David Chelliah

Reputation: 1349

Set the max-width of the image as 100%. Height should be set to auto.

Solution 1 : When the image can grow up to its parent div's width:

.wrapper {
  width: 500px;
  height: 500px;
  border: 1px solid red;
  position: absolute;
}
.wrapper img {
  /*width:100%;*/
  height: auto;
  max-width: 100%;
}
<div class="wrapper">

  <img src="https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">

</div>

Solution 2 : Initially the image width will be restricted by the max-width property to stay within the thumbnail size.

Onclick of image, remove the thumbnail class, so that it naturally over flows the parent to its original size

.wrapper {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  /*position: absolute;*/
}
.wrapper img.thumbnail {
  /*width:100%;*/
  height: auto;
  max-width: 100%;
}
<div class="wrapper">
  Initially
  <img class="thumbnail" src="https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">

</div>

<div class="wrapper">
  On click
  <img src="https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">

</div>

Upvotes: 1

Related Questions