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

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: stackoverflow.com - 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.

This question is related to html css image autoresize

The answer is


You can set the image as the background to a div, and then use the CSS background-size property:

background-size: cover;

It will "Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area" -- W3Schools


<style type="text/css">
    #container{
        text-align: center;
        width: 100%;
        height: 200px; /* Set height */
        margin: 0px;
        padding: 0px;
        background-image: url('../assets/images/img.jpg');
        background-size: content; /* Scaling down large image to a div */
        background-repeat: no-repeat;
        background-position: center;
    }
</style>

<div id="container>
    <!-- Inside container -->
</div>

I have much better solution without need of any JavaScript. It is fully responsive, and I use it a lot. You often need to fit an image of any aspect ratio to a container element with a specified aspect ratio. And having whole this thing fully responsive is a must.

_x000D_
_x000D_
/* For this demo only */_x000D_
.container {_x000D_
  max-width: 300px;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
.img-frame {_x000D_
  box-shadow: 3px 3px 6px rgba(0, 0, 0, .15);_x000D_
  background: #ee0;_x000D_
  margin: 20px auto;_x000D_
}_x000D_
_x000D_
/* This is for responsive container with specified aspect ratio */_x000D_
.aspect-ratio {_x000D_
  position: relative;_x000D_
}_x000D_
.aspect-ratio-1-1 {_x000D_
  padding-bottom: 100%;_x000D_
}_x000D_
.aspect-ratio-4-3 {_x000D_
  padding-bottom: 75%;_x000D_
}_x000D_
.aspect-ratio-16-9 {_x000D_
  padding-bottom: 56.25%;_x000D_
}_x000D_
_x000D_
/* This is the key part - position and fit the image to the container */_x000D_
.fit-img {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: auto;_x000D_
  max-width: 80%;_x000D_
  max-height: 90%_x000D_
}_x000D_
.fit-img-bottom {_x000D_
  top: auto;_x000D_
}_x000D_
.fit-img-tight {_x000D_
  max-width: 100%;_x000D_
  max-height: 100%_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
  <div class="aspect-ratio aspect-ratio-1-1 img-frame">_x000D_
    <img src="//placehold.it/400x300" class="fit-img" alt="sample">_x000D_
  </div>_x000D_
_x000D_
  <div class="aspect-ratio aspect-ratio-4-3 img-frame">_x000D_
    <img src="//placehold.it/400x300" class="fit-img fit-img-tight" alt="sample">_x000D_
  </div>_x000D_
_x000D_
  <div class="aspect-ratio aspect-ratio-16-9 img-frame">_x000D_
    <img src="//placehold.it/400x400" class="fit-img" alt="sample">_x000D_
  </div>_x000D_
_x000D_
  _x000D_
  <div class="aspect-ratio aspect-ratio-16-9 img-frame">_x000D_
    <img src="//placehold.it/300x400" class="fit-img fit-img-bottom" alt="sample">_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

You can set max-width and max height independently; the image will respect the smallest one (depending on the values and aspect ratio of the image). You can also set image to be aligned as you want (for example, for a product picture on an infinite white background you can position it to center bottom easily).


I fixed this problem using the following code:

<div class="container"><img src="image_url" /></div>
.container {
    height: 75px;
    width: 75px;
}

.container img {
    object-fit: cover;
    object-position: top;
    display: block;
    height: 100%;
    width: 100%;
}

This solution doesn't stretch the image and fills the whole container, but it cuts some of the image.

HTML:

 <div><img src="/images/image.png"></div>

CSS:

div {
    width: 100%;
    height: 10em;
    overflow: hidden;

img {
    min-width: 100%;
    min-height: 100%;
}

Define the div simply like:

div.headerimg1 {
   position: absolute;
   top: 290px;
   left: 81px;
   width: 389px;
   height: 349px;
}

<div class="headerimg1">
    <img src="" style="max-height:100%;height:auto;width:100%;max-width:100%;margin:auto;display:inline;">
</div>

A simple solution (4-step fix!!) that seems to work for me, is below. The example uses the width to determine the overall size, but you can also flip it to use the height instead.

  1. Apply CSS styling to the image container (for example, <img>)
  2. Set the width property to the dimension you want
    • For dimensions, use % for relative size, or autoscaling (based on image container or display)
    • Use px (or other) for a static, or set dimension
  3. Set the height property to automatically adjust, based on the width
  4. ENJOY!

For example,

<img style="width:100%; height:auto;"
    src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"
/>

A beautiful hack.

You have two ways of making the image responsive.

  1. When an image is a background image.
#container{
    width: 300px;
    height: 300px;
    background-image: url(http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
}

<div id="container"><div>

Run it here


But one should use img tag to put images as it is better than background-image in terms of SEO as you can write keyword in the alt of the img tag. So here is you can make the image responsive.

  1. When image is in img tag.
#container{
    max-width: 400px;
    overflow: hidden;
}
img{
    width: 100%;
    object-fit: contain;
}

<div id="container">
   <img src="http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/>
<div>

Run it here


I centered and scaled proportionally an image inside a hyperlink both horizontally and vertically this way:

#link {
    border: 1px solid blue;
    display: table-cell;
    height: 100px;
    vertical-align: middle;
    width: 100px;
}
#link img {
    border: 1px solid red;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-height: 60px;
    max-width: 60px;
}

It was tested in Internet Explorer, Firefox, and Safari.

More information about centering is here.


A simple solution is to use flexbox. Define the container's CSS to:

.container{
    display: flex;
    justify-content: center;
    align-items: center;
    align-content: center;
    overflow: hidden;
    /* Any custom height */
}

Adjust the contained image width to 100% and you should get a nice centered image in the container with the dimensions preserved.


The solution is easy with a bit of maths...

Just put the image in a div and then in the HTML file where you specify the image. Set the width and height values in percentages using the pixel values of the image to calculate the exact ratio of width to height.

For example, say you have an image that has a width of 200 pixels and a height of 160 pixels. You can safely say that the width value will be 100%, because it is the larger value. To then calculate the height value you simply divide the height by the width which gives the percentage value of 80%. In the code it will look something like this...

<div class="image_holder_div">
    <img src="some_pic.png" width="100%" height="80%">
</div>

All the provided answers, including the accepted one, work only under the assumption that the div wrapper is of a fixed size. So this is how to do it whatever the size of the div wrapper is and this is very useful if you develop a responsive page:

Write these declarations inside your DIV selector:

width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */

Then put these declarations inside your IMG selector:

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

VERY IMPORTANT:

The value of maxHeight must be the same for both the DIV and IMG selectors.


The following works perfectly for me:

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

Here is a solution that will both vertically and horizontally align your img within a div without any stretching even if the image supplied is too small or too big to fit in the div.

The HTML content:

<div id="myDiv">
  <img alt="Client Logo" title="Client Logo" src="Imagelocation" />
</div>

The CSS content:

#myDiv
{
  height: 104px;
  width: 140px;
}
#myDiv img
{
  max-width: 100%;
  max-height: 100%;
  margin: auto;
  display: block;
}

The jQuery part:

var logoHeight = $('#myDiv img').height();
    if (logoHeight < 104) {
        var margintop = (104 - logoHeight) / 2;
        $('#myDiv img').css('margin-top', margintop);
    }

U use the following class to solve this problem;

.custom-image{height: auto; width: auto; max-height: 100%; max-width: 100%; object-fit: contain;}

If you're using Bootstrap, you just need to add the img-responsive class to the img tag:

<img class="img-responsive" src="img_chania.jpg" alt="Chania">

Bootstrap Images


object-fit

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.

Fiddle: http://jsfiddle.net/mbHB4/7364/


As answered here, you can also use vh units instead of max-height: 100% if it doesn't work on your browser (like Chrome):

img {
    max-height: 75vh;
}

Give the height and width you need for your image to the div that contains the <img> tag. Don't forget to give the height/width in the proper style tag.

In the <img> tag, give the max-height and max-width as 100%.

<div style="height:750px; width:700px;">
    <img alt="That Image" style="max-height:100%; max-width:100%;" src="">
</div>

You can add the details in the appropriate classes after you get it right.


This article may help u

_x000D_
_x000D_
  .square {
     position: relative;
     width: 300px;     
     height: 300px;
     overflow: hidden;
  }
  img {
     position: absolute;
     max-width: 100%;
     width: 100%;
     height: auto;
     top: 50%;     
     left: 50%;
     transform: translate( -50%, -50%);
 }
  img.landscape {
    height: 100%;
    width: auto;
}
_x000D_
<div class="square">
   <img src="https://unsplash.it/400/500" alt="Image" /> 
</div>
<div class="square">
   <img src="https://unsplash.it/500/400" class="landscape" alt="Image" /> 
</div>
_x000D_
_x000D_
_x000D_

https://medium.com/@kimcodeashian/simple-css-solutions-how-to-resize-images-with-different-dimensions-without-cropping-eb744e93246d

_x000D_
_x000D_
  .square {
     position: relative;
     width: 441px;     
     height: 200px;
     overflow: hidden;
     border:1px solid black;
  }
  img {
     max-width: 100%;
/*     width: 100%;*/
     height: auto;
/*     transform: translate( -50%, -50%);*/
 }
  img.landscape {
    height: 100%;
    width: auto;
}
_x000D_
<div class="square">
   <img src="https://cdn.pixabay.com/photo/2020/08/28/12/32/man-5524488__340.jpg" alt="Image" /> 
</div>
_x000D_
_x000D_
_x000D_


I just published a jQuery plugin that does exactly what you need with a lot of options:

https://github.com/GestiXi/image-scale

Usage:

HTML

<div class="image-container">
    <img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg">
</div>

JavaScript

$(function() {
    $("img.scale").imageScale();
});

Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.

To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.

Choosing whether to do height or width depends on your image and container dimensions:

  1. If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
  2. If your image is portrait, and your container is landscape, you must set height="100%" on the image.
  3. If your image is landscape, and your container is portrait, you must set width="100%" on the image.

If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.

You just have to ensure that the SVG file has none of these properties set in the <svg> tag:

height
width
viewbox

Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.


You have to tell the browser the height of where you are placing it:

.example {
    height: 220px; /* DEFINE HEIGHT */
    background: url('../img/example.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

Make it simple!

Give the container a fixed height and then for the img tag inside it, set width and max-height.

<div style="height: 250px">
     <img src="..." alt=" " style="width: 100%;max-height: 100%" />
</div>

The difference is that you set the width to be 100%, not the max-width.


Edit: Previous table-based image positioning had issues in Internet Explorer 11 (max-height doesn't work in display:table elements). I've replaced it with inline based positioning which not only works fine in both Internet Explorer 7 and Internet Explorer 11, but it also requires less code.


Here is my take on the subject. It'll only work if the container has a specified size (max-width and max-height don't seem to get along with containers that don't have concrete size), but I wrote the CSS content in a way that allows it to be reused (add picture-frame class and px125 size class to your existing container).

In CSS:

.picture-frame
{
    vertical-align: top;
    display: inline-block;
    text-align: center;
}

.picture-frame.px125
{
    width: 125px;
    height: 125px;
    line-height: 125px;
}

.picture-frame img
{
    margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
    max-width: 100%;
    max-height: 100%;
    display: inline-block;
    vertical-align: middle;
    border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}

And in HTML:

<a href="#" class="picture-frame px125">
    <img src="http://i.imgur.com/lesa2wS.png"/>
</a>

DEMO

_x000D_
_x000D_
/* Main style */_x000D_
_x000D_
.picture-frame_x000D_
{_x000D_
    vertical-align: top;_x000D_
    display: inline-block;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.picture-frame.px32_x000D_
{_x000D_
    width: 32px;_x000D_
    height: 32px;_x000D_
    line-height: 32px;_x000D_
}_x000D_
_x000D_
.picture-frame.px125_x000D_
{_x000D_
    width: 125px;_x000D_
    height: 125px;_x000D_
    line-height: 125px;_x000D_
}_x000D_
_x000D_
.picture-frame img_x000D_
{_x000D_
    margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */_x000D_
    max-width: 100%;_x000D_
    max-height: 100%;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
    border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */_x000D_
}_x000D_
_x000D_
/* Extras */_x000D_
_x000D_
.picture-frame_x000D_
{_x000D_
    padding: 5px;_x000D_
}_x000D_
_x000D_
.frame_x000D_
{_x000D_
    border:1px solid black;_x000D_
}
_x000D_
<p>32px</p>_x000D_
<a href="#" class="picture-frame px32 frame">_x000D_
    <img src="http://i.imgur.com/lesa2wS.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px32 frame">_x000D_
    <img src="http://i.imgur.com/kFMJxdZ.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px32 frame">_x000D_
    <img src="http://i.imgur.com/BDabZj0.png"/>_x000D_
</a>_x000D_
<p>125px</p>_x000D_
<a href="#" class="picture-frame px125 frame">_x000D_
    <img src="http://i.imgur.com/lesa2wS.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px125 frame">_x000D_
    <img src="http://i.imgur.com/kFMJxdZ.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px125 frame">_x000D_
    <img src="http://i.imgur.com/BDabZj0.png"/>_x000D_
</a>
_x000D_
_x000D_
_x000D_


Edit: Possible further improvement using JavaScript (upscaling images):

function fixImage(img)
{
    var $this = $(img);
    var parent = $this.closest('.picture-frame');
    if ($this.width() == parent.width() || $this.height() == parent.height())
        return;

    if ($this.width() > $this.height())
        $this.css('width', parent.width() + 'px');
    else
        $this.css('height', parent.height() + 'px');
}

$('.picture-frame img:visible').each(function
{
    if (this.complete)
        fixImage(this);
    else
        this.onload = function(){ fixImage(this) };
});

Check my answer, Make an image responsive - simplest way -

img{
    width: 100%;
    max-width: 800px;
}

The accepted answer from Thorn007 doesn't work when the image is too small.

To solve this, I added a scale factor. This way, it makes the image bigger and it fills the div container.

Example:

<div style="width:400px; height:200px;">
  <img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>

Notes:

  1. For WebKit you must add -webkit-transform:scale(4); -webkit-transform-origin:left top; in the style.
  2. With a scale factor of 4, you have max-width = 400/4 = 100 and max-height = 200/4 = 50
  3. An alternate solution is to set max-width and max-height at 25%. It's even simpler.

The simplest way to do this is by using object-fit:

<div class="container">
  <img src="path/to/image.jpg">
</div>

.container{
   height: 300px;
}

.container img{
  height: 100%;
  width: 100%;
  object-fit: cover;
}

If you're using Bootstrap, just add the img-responsive class and change to

.container img{
    object-fit: cover;
}

I see that many people have suggested object-fit which is a good option. But if you want it to work in older browsers as well, there is another way of doing it easily.

Its quite simple. The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Once it is in the centre, I give to the image,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.


Here is a demonstration of the above logic.

https://jsfiddle.net/furqan_694/s3xLe1gp/

This logic works in all browsers.


Check out my solution: http://codepen.io/petethepig/pen/dvFsA

It's written in pure CSS, without any JavaScript code. It can handle images of any size and any orientation.

Given such HTML:

<div class="image">
  <div class="trick"></div>
  <img src="http://placekitten.com/415/200"/>
</div>

the CSS code would be:

.image {
  font-size: 0;
  text-align: center;
  width: 200px;  /* Container's dimensions */
  height: 150px;
}
img {
  display: inline-block;
  vertical-align: middle;
  max-height: 100%;
  max-width: 100%;
}
.trick {
  display: inline-block;
  vertical-align: middle;
  height: 150px;
}

The code below is adapted from previous answers and is tested by me using an image called storm.jpg.

This is the complete HTML code for a simple page that displays the image. This works perfect and was tested by me with www.resizemybrowser.com. Put the CSS code at the top of your HTML code, underneath your head section. Put the picture code wherever you want the picture.

<html>
    <head>
        <style type="text/css">
            #myDiv
            {
                  height: auto;
                  width: auto;
            }
            #myDiv img
            {
                max-width: 100%;
                max-height: 100%;
                margin: auto;
                display: block;
            }
        </style>
    </head>

    <body>
        <div id="myDiv">
            <img src="images/storm.jpg">
        </div>
    </body>
</html>

Or you can simply use:

background-position:center;
background-size:cover;

Now the image will take all the space of the div.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to autoresize

A div with auto resize when changing window width\height Scale image to fit a bounding box How to make a Qt Widget grow with the window size? Android: why is there no maxHeight for a View? How do I auto-resize an image to fit a 'div' container? How to get StackPanel's children to fill maximum space downward?