1746

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.

Liam
  • 22,818
  • 25
  • 93
  • 157
001
  • 55,049
  • 82
  • 210
  • 324
  • 1
    Some interesting libraries for doing image resizing to fit the container: * http://plugins.jquery.com/project/myimgscale * http://code.google.com/p/jquery-imagefit-plugin/ – Frosty Z Jul 13 '11 at 13:10
  • Aside @Kevin's answer... You can also use services like ImageBoss to create your images with the size you want, on-demand. Fitting the image on the container is great but serving images responsively is way batter. – Igor Escobar May 24 '18 at 21:35
  • Posible duplicate: https://stackoverflow.com/questions/1891857/how-do-you-stretch-an-image-to-fill-a-div-while-keeping-the-images-aspect-rat – jolumg Oct 17 '18 at 10:33
  • @jolumg Not quite; while there's a lot of overlap in some solutions, there are also many solutions that are not interchangeable, as that one is asking how to scale an image up, whereas this one is asking to scale an image down. – TylerH Jan 02 '19 at 15:37

37 Answers37

2125

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

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

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

Example: http://jsfiddle.net/xwrvxser/1/

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="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Landscape Div
<div class="landscape">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Square Div
<div class="square">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Kevin
  • 22,680
  • 2
  • 17
  • 21
522

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/

TylerH
  • 19,065
  • 49
  • 65
  • 86
Shih-Min Lee
  • 7,197
  • 7
  • 32
  • 61
  • 53
    This will scale the image to fit the larger dimension completely within the container, so the smaller dimension may not cover it completely. To crop the larger dimension instead, use `object-fit: cover` – Gabriel Grant Oct 20 '15 at 17:08
  • 5
    Worked for me - compared to the solution of @KevinD - this has NOT changed the proportions in edge cases. Cheers! – Barnabas Kecskes Nov 13 '15 at 14:23
  • 10
    Will be great when fully supported. Atm, neither IE nor edge support it unfortunately. – spectras Feb 16 '16 at 00:48
  • This solution is amazing and saved me hours of fiddling. This is especially useful if you don't know whether the image will be portrait or landscape. – Eckstein Sep 26 '16 at 03:05
  • 3
    If you want to set max-width and max-height you can do that. Works perfectly . – Sandip Subedi Mar 21 '17 at 05:42
  • 4
    Seems that cant be used with IE11 and edge 14 / 15 though -> https://caniuse.com/#search=object-fit – mcorbe Jun 20 '17 at 09:39
  • 1
    There's a polyfill for older browsers: https://github.com/fregante/object-fit-images – gib Jul 24 '19 at 15:13
  • @dota2pro Please note that it's a license violation to copy substantive code of someone else's from JSFiddle or similar sites over to Stack Overflow. – TylerH Nov 14 '19 at 14:56
  • @TylerH never heard that one before, Anyway if the Jsfiddle gets deleted we will just remove this answer then – dota2pro Nov 14 '19 at 15:55
  • @dota2pro Yes, it's OP's responsibility to make their post abide by the rules; that's why we have such standards to begin with. Re: never heard that one before - content on SO is licensed under CC-by SA 3.0 (or 4.0 after some date recently, I forget exactly when); that creates irrevocable permissions/authority. It's a violation of the license to post stuff under that license that you aren't authorized to do so to begin with. JSFiddle doesn't explicitly state what license content on its website is under, so it could be something very restrictive either with JSFiddle in control or OP. – TylerH Nov 14 '19 at 16:29
  • @dota2pro However, even if the JSFiddle were removed from this answer, it would not be delete-worthy at all. Without the JSFiddle, it provides a correct answer *and* code to do it. The JSFiddle is just a link to a *runnable* example, which is not something SO answers are required to have. – TylerH Nov 14 '19 at 16:30
  • 1
    @TylerH thanks for the info, As long as the `FBI` doesn't show up on my front door it's all good :D – dota2pro Nov 14 '19 at 16:50
  • 1
    This doesn't work if the parent are set to `100%` `height/width`. It makes them stretch and introduces a scroll bar. This is not desired. How to fix that is parent is set to `100%` then image should resize as per the parent ? – SimpleGuy Aug 21 '20 at 15:34
  • I'm having a really hard time getting this to work but I don't know if it's because it's not playing nicely with my container heirarchy which is based on display:grid and percentages or if it's because I have multiple images in the div which all need to be scaled on one size. – Michael Sep 08 '20 at 00:10
  • @PromisePreston please do not edit your own answer into other people's answer. Post your own instead (if it is unique, which this one isn't). Likewise, especially don't edit *non-CSS* into a CSS answer. – TylerH Sep 17 '20 at 21:17
  • @TylerH, I added another perspective to the answer which some persons might find useful. So instead of creating my own answer I just thought of adding it to it. – Promise Preston Sep 18 '20 at 12:15
  • ```object-fit: contain'``` has an issue when you want to have `border-radius` on the image. – vanduc1102 Nov 22 '20 at 05:49
111

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.

Neil
  • 20,635
  • 14
  • 48
  • 68
  • 2
    Is it just me or are there several mistakes in this post? " 'portrait shaped' or both 'landscape shaped' (wider than they are tall, and taller than they are wide, respectively)" ... shouldn't your "respectives" be switched around? And in your bullet points 2. and 3., they both say "you must set width="100%" on the image". I'm guessing you copy-pasted and forgot to change one of those to "height" rather than "width". – Buttle Butkus Dec 04 '11 at 11:43
  • Just fixed it. 2 and 3 may now be both wrong or both right, instead of one being wrong and one being right. I can't remember what the correct answer is. ;) – Neil Dec 05 '11 at 05:33
  • 2
    "Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files."? This seems just incorrect. @Thorn007's answer provides such a way, and I've used it myself - http://stackoverflow.com/questions/12259736/why-are-images-centered-vertically-with-line-height-positioned-2-pixels-below – Dan Dascalescu Sep 06 '12 at 06:03
  • @DanDascalescu Thorn007's answer doesn't expand the image if it is smaller than the container. The best solution nowadays is to use an element with a background image and set `background-size: contain`. – Kevin Borders Oct 09 '14 at 22:42
85

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);
    }
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Humble Rumble
  • 1,060
  • 7
  • 15
52

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mehdi Maghrouni
  • 1,409
  • 21
  • 23
41

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(https://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.

  2. When image is in img tag.

    #container{
        max-width: 400px;
        overflow: hidden;
    }
    img{
        width: 100%;
        object-fit: contain;
    }
    
    <div id="container">
        <img src="https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/>
    <div>
    

    Run it here

TylerH
  • 19,065
  • 49
  • 65
  • 86
Siraj Alam
  • 5,569
  • 5
  • 39
  • 55
24

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Chuck Dries
  • 1,510
  • 10
  • 18
  • I believe by "fit a div container" the OP meant that the image should not extend beyond the containing element in either dimension. In @JonatasWalker 's solution, the image is cropped. Also a background solution might not be semantically correct, depending on the situation. For example, you might need `alt` values and such things (though you can also add a dummy image which is invisible to non-assistant technologies), or you might need to make it clickable. – Balázs Apr 10 '17 at 11:49
  • @Balázs ah in this case the correct setting would be `background-size: contain` and I think I'd personally go the dummy image route just because there's no really an easy way to do what's described here without JavaScript – Chuck Dries Apr 10 '17 at 11:50
  • @ChuckDries I am not really sure what you mean, the accepted answer solves the problem. – Balázs Apr 10 '17 at 11:54
22

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;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
dmitry
  • 351
  • 3
  • 4
10

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();
});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Nicolas BADIA
  • 5,065
  • 6
  • 39
  • 45
10

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%;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Miia Klingstedt
  • 111
  • 1
  • 5
10

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.

It's 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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Furqan Rahamath
  • 1,612
  • 1
  • 15
  • 23
9

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.

/* For this demo only */
.container {
  max-width: 300px;
  margin: 0 auto;
}
.img-frame {
  box-shadow: 3px 3px 6px rgba(0, 0, 0, .15);
  background: #ee0;
  margin: 20px auto;
}

/* This is for responsive container with specified aspect ratio */
.aspect-ratio {
  position: relative;
}
.aspect-ratio-1-1 {
  padding-bottom: 100%;
}
.aspect-ratio-4-3 {
  padding-bottom: 75%;
}
.aspect-ratio-16-9 {
  padding-bottom: 56.25%;
}

/* This is the key part - position and fit the image to the container */
.fit-img {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  max-width: 80%;
  max-height: 90%
}
.fit-img-bottom {
  top: auto;
}
.fit-img-tight {
  max-width: 100%;
  max-height: 100%
}
<div class="container">

  <div class="aspect-ratio aspect-ratio-1-1 img-frame">
    <img src="//placehold.it/400x300" class="fit-img" alt="sample">
  </div>

  <div class="aspect-ratio aspect-ratio-4-3 img-frame">
    <img src="//placehold.it/400x300" class="fit-img fit-img-tight" alt="sample">
  </div>

  <div class="aspect-ratio aspect-ratio-16-9 img-frame">
    <img src="//placehold.it/400x400" class="fit-img" alt="sample">
  </div>

  
  <div class="aspect-ratio aspect-ratio-16-9 img-frame">
    <img src="//placehold.it/300x400" class="fit-img fit-img-bottom" alt="sample">
  </div>
  
</div>

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).

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
actimel
  • 426
  • 4
  • 20
8

The following works perfectly for me:

img{
   height: 99999px;
   object-fit:contain;
   max-height: 100%;
   max-width: 100%;    
   display: block;
   margin: auto auto;
}
Chong Lip Phang
  • 6,658
  • 5
  • 49
  • 71
7

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%;
}
TylerH
  • 19,065
  • 49
  • 65
  • 86
Serkan KONAKCI
  • 524
  • 6
  • 7
6
<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>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
easd
  • 61
  • 1
  • 1
  • 2
    If you could add some explanation of your code that would be nice (I know you have some comments there but just a few words about why/how this answers the question would make it look much better). – display-name-is-missing May 28 '14 at 14:25
5

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
bancer
  • 7,040
  • 7
  • 35
  • 57
5

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
AZD
  • 61
  • 1
  • 2
5

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>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
dan
  • 51
  • 1
  • 1
5

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;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Rick
  • 10,168
  • 2
  • 38
  • 40
5

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

/* Main style */

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

.picture-frame.px32
{
    width: 32px;
    height: 32px;
    line-height: 32px;
}

.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 */
}

/* Extras */

.picture-frame
{
    padding: 5px;
}

.frame
{
    border:1px solid black;
}
<p>32px</p>
<a href="#" class="picture-frame px32 frame">
    <img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
    <img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
    <img src="http://i.imgur.com/BDabZj0.png"/>
</a>
<p>125px</p>
<a href="#" class="picture-frame px125 frame">
    <img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
    <img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
    <img src="http://i.imgur.com/BDabZj0.png"/>
</a>

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) };
});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jahu
  • 4,899
  • 2
  • 35
  • 55
  • There is a drawback to using this method. If the image fails to load, alt text will be displayed with parent container `line-height`. If alt text has more than one line, it will start looking really bad... – jahu Jan 19 '16 at 12:49
5

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;
}
Community
  • 1
  • 1
gaborous
  • 12,649
  • 7
  • 73
  • 94
  • 1
    [Do you mean `vh`](https://developer.mozilla.org/en/docs/Web/CSS/length#Viewport-percentage_lengths)? and what doesn't work in Chrome? – misterManSam May 30 '16 at 02:59
  • 1
    @misterManSam Yes thank you very much, was too tired yesterday when I posted this answer. `max-height: xx%` (percentage unit) doesn't work in Chrome with some elements like `img`, but `vh` unit does. However, percentages work with `height`, `width`, `max-width`, etc. – gaborous May 30 '16 at 10:49
4

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.
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user217447
  • 143
  • 2
  • 3
  • 1
    This is not a very reliable solution if you're trying to support the whole market. I steer clear of CSS3 unless you're going to have some sort of a fallback for browsers that don't support it. – dudewad Oct 10 '14 at 19:33
4

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"
/>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • Thank you very much, I used it in a Webview inside Android. I changed the width to 80% to simulate a margin ^^' – naitbrahim Nov 15 '20 at 22:09
4

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mateo Marin
  • 159
  • 6
3

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Billal Begueradj
  • 13,551
  • 37
  • 84
  • 109
3

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
HoangYell
  • 1,967
  • 22
  • 21
1

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>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user2796283
  • 243
  • 4
  • 8
1

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;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Joseph Lariosa
  • 335
  • 1
  • 3
  • 13
0

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

img{
    width: 100%;
    max-width: 800px;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Abhishek Goel
  • 15,517
  • 8
  • 81
  • 62
0

As seen in my 2014 Codepen example, I've made a solution that would work for any unknown combination of width/height (aspect-ratio) with the help of a as little javascript as possible, to change the CSS of how the image is centered when the aspect-ratio of the container changes above/below the aspect ratio of the image:

Try resizing the container by dragging the bottom right corner:

// Detects when the window width is too narrow for the current image 
// aspect-ratio, and fits it to height 100% instead of width 100%.
const photo = document.images[0]

const onPhotoResize = new ResizeObserver(entries => 
  window.requestAnimationFrame(checkRatio)
)

onPhotoResize.observe(photo.parentNode)

function checkRatio(){
  const photoParent = photo.parentNode,
        imageAspectRatio = photo.clientWidth / photo.clientHeight,
        parentAspectRatio = photoParent.clientWidth / photoParent.clientHeight
        
  photo.classList[imageAspectRatio > parentAspectRatio ? 'add':'remove']('max')
}
.box{
  width: 20%;
  height: 60%;
  margin: auto;
  position: absolute;
  top:0; left:0; right:0; bottom:0;
  resize: both;
  overflow: hidden;
  border: 5px solid red;
 } 

.box > img{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100%;
    transform: translate(-50%, -50%); 
}

.box > img.max{ width:auto; height:100%; }
<div class='box'>
  <img src="https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg">
</div>
vsync
  • 87,559
  • 45
  • 247
  • 317
0

This was my solution. You will need to have the picture inserted twice. But it does not use js, and the img will resize to both width and height. You can click on 'run code snippet - full page', open dev console and resize window-width to see the responsive effect.

    /* responsive width */
      .responsivewidth{
        background: lightsalmon;
        height: 100px;
        width: 50%;
      }
      /* Widthlimit */
      .maxedbywidth {
        background: navy;
        height: 200px;
        width: 100px;
      }
      .div1 {
        max-height: 100%;
        position: relative;
        box-sizing: content-box;

        /* Center: */
        top: 50%;
        transform: translateY(-50%);
      }
      .margerimg {
        height: auto;
        max-width: 100%;
        opacity: 0;
      }
      .div2 {
        height: 100%;
        width: fit-content;
        position: absolute;
        top: 0;

        /* Center: */
        left: 50%;
        transform: translateX(-50%);
      }
      .mainimg {
        max-height: 100%;
        max-width: 100%;
      }
<div class="responsivewidth">
      <div class="div1">
        <img class="margerimg" src="https://via.placeholder.com/2000x1500" />
        <div class="div2">
          <img class="mainimg" src="https://via.placeholder.com/2000x1500" />
        </div>
      </div>
    </div>
    <div class="maxedbywidth">
      <div class="div1">
        <img class="margerimg" src="https://via.placeholder.com/2000x1500" />
        <div class="div2">
          <img class="mainimg" src="https://via.placeholder.com/2000x1500" />
        </div>
      </div>
    </div>
Servus
  • 314
  • 1
  • 8
  • Having to insert the image twice (or four times in your actual demo) seems less than ideal compared to some of the other solutions here which just require a CSS property or three. – TylerH May 03 '21 at 13:41
  • None of them worked for me *the way I need it to – Servus May 03 '21 at 14:45
  • I just felt like sharing my solution, maybe helping someone in the process. I actually think its a very nice bit of code you can apply as technique if you understand it. But I don't feel its right to criticise it, if you don't at least take the time to understand it. It's actually 2 pics u need – Servus May 03 '21 at 15:03
0

There are several ways to fit the image to <div>.

img {
    object-fit: cover;
}

The CSS object-fit property is used to specify how an <img> or <video> should be resized to fit its container.

This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible".

  • fill - This is default. The image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit
  • contain - The image keeps its aspect ratio, but is resized to fit within the given dimension
  • cover - The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit
  • none - The image is not resized
  • scale-down - the image is scaled down to the smallest version of none or contain

You can find out more working samples here.

Sergio Reis
  • 856
  • 7
  • 27
  • This just repeats the same answer as the existing 2nd-highest scoring answer from *2015*. Please take care not to repeat existing answers. – TylerH May 06 '21 at 15:32
-1

You use the following class to solve this problem;

.custom-image{height: auto; width: auto; max-height: 100%; max-width: 100%; object-fit: contain;}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Albert Alberto
  • 419
  • 4
  • 10
-1

This article may help you:

  .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;
}
<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>

Simple CSS Solutions: How to fit images with different dimensions in set containers (2017-05-01)

  .square {
     position: relative;
     width: 441px;
     height: 200px;
     overflow: hidden;
     border:1px solid black;
  }
  img {
     max-width: 100%;
/*     width: 100%;*/<----it stretch image and fit into the parent
     height: auto;
/*     transform: translate( -50%, -50%);*/<-----set vertically and horizontally center
 }
  img.landscape {
    height: 100%;
    width: auto;
}
<div class="square">
   <img src="https://cdn.pixabay.com/photo/2020/08/28/12/32/man-5524488__340.jpg" alt="Image" />
</div>
ßãlãjî
  • 1,865
  • 2
  • 14
  • 22
-1

Using max-height: 100% from a previous answer allowed the image to be resized according to the containing window resizing when the window was pulled/extended from the horizontal edges. Pulled from the bottom, would slice the visibility of the image if brought up, instead of scaling the image. Then using, max-height: 75vh; allowed the image to be scaled if pulled from the bottom but not the sides. Putting both together gave results to scale the image according to the container pulled in both directions;

.myPics {
  max-height: 75vh;
  max-width: 100%;
}

or you can use

.myPics {  
  width: 90%;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
Vass
  • 2,303
  • 10
  • 35
  • 54
-2

Or you can simply use:

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

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

Knetic
  • 1,880
  • 1
  • 19
  • 32
Sharifur Robin
  • 190
  • 1
  • 2
  • 12
-5

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>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123