How do I auto-resize an image to fit a 'div' container?

Asked 12 years ago
Viewed 3.04 k times

How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining its width:height ratio?

Example: - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.

asked 12 years ago

Correct Answer

Do not apply an explicit width or height to the image tag. Instead, give it:


Also, height: auto; if you want to specify a width only.


img {
    max-width: 100%;
    max-height: 100%;

.portrait {
    height: 80px;
    width: 30px;

.landscape {
    height: 30px;
    width: 80px;

.square {
    height: 75px;
    width: 75px;
Portrait Div
<div class="portrait">
    <img src="">

Landscape Div
<div class="landscape">
    <img src="">

Square Div
<div class="square">
    <img src="">
answered 2 years ago

Other Answer


It turns out there's another way to do this.

<img style='height: 100%; width: 100%; object-fit: contain'/>

will do the work. It's CSS 3 stuff.


answered 12 years ago