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="https://via.placeholder.com/200x200.jpg"/>
</div>
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%;
}
<div>
<img src="https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg">
</div>
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
You can do it like this :
// Get your image tag
var img = document.getElementById("yourImage");
// Set its src
img.src = "https://www.tictactrip.eu/react-app/company-searchHeader-sncf.jpg";
// Wait for it to load
img.addEventListener("load", function() {
if (img.width > img.height) {
img.style.width = "100%";
} else {
img.style.height = "100%";
}
});
#yourDiv {
width: 100px;
height: 150px;
position: relative;
border: 1px solid red;
}
<div id="yourDiv">
<img id="yourImage"/>
</div>
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.
For example,
<div style="width: 100px; height: 150px">
<img/>
</div>
I want the img
to be as large as possible, but
- always confined by the
div
, aka, no part of the img
is outside or overhidden by the div
.
- 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?
Thanks!
@lawrence-witt Thank you so much. You want to make it an answer? I will accept it
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,