Solution 1 :

As mentioned in the comments, using object-fit: contain will achieve your desired result. Here is a 200x200px image being contained within a 150x100px div:

.container {
  width: 150px;
  height: 100px;
  border: 1px solid red;

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
<div class="container">
  <img src=""/>

Solution 2 :

you can set the width and the height of div which is parent of img and set the height and width sizes to 100% to make it fit in the parent div and it not overflow no more

div {
  position: relative;
  width: 300px;
  height: 300px;
  border: 1px solid blue;

img {
  width: 100%;
  height: 100%;
  <img src="">

And as you can see in the bellow example parent div which has blue border color have an image inside and the image is fit into try to adjust the width and height of parent div and you will just see your self how the image will increase too in order to fit into its parent

Solution 3 :

You can do it like this :

// Get your image tag
var img = document.getElementById("yourImage");

// Set its src
img.src = "";

// Wait for it to load
img.addEventListener("load", function() {
    if (img.width > img.height) { = "100%";
    } else { = "100%";
#yourDiv {
  width: 100px;
  height: 150px;
  position: relative;
  border: 1px solid red;
<div id="yourDiv">
    <img id="yourImage"/>

You can eventually use flexboxes to make the image centered in the div.
When you specify only the width/height of an image in CSS, the other dimension will be computed automatically preserving aspect ratio.
Your div must have position: relative; for the child image to fit in.

Problem :

For example,

<div style="width: 100px; height: 150px">

I want the img to be as large as possible, but

  1. always confined by the div, aka, no part of the img is outside or overhidden by the div.
  2. the img keeps its aspect-ratio.

It is like keep magnifying the image, and stop as soon as either its height or width hits the border of the div.

Is there any convenient way to achieve this?



Comment posted by object-fit

You have a few different options if you use

Comment posted by powerseed

@lawrence-witt Thank you so much. You want to make it an answer? I will accept it

Comment posted by Hicka

In this case aspect ratio isn’t conserved

Comment posted by powerseed

Sry I cannot accept this as the aspect ratio isn’t conserved

Comment posted by Umutambyi Gad

I guess bellow was what you wanted

Comment posted by powerseed

Thank you, I believe your code is correct, but I cannot accept it as it is not the simplest way. As lawrence-witt pointed out,