[html] Scale image to fit a bounding box

Is there a css-only solution to scale an image into a bounding box (keeping aspect-ratio)? This works if the image is bigger than the container:

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

Example:

But I want to scale up the image until a dimension is 100% of the container.

This question is related to html css image resize autoresize

The answer is


.boundingbox {
    width: 400px;
    height: 500px;
    border: 2px solid #F63;
}
img{
    width:400px;
    max-height: 500px;
    height:auto;
}

I'm editing my answer to further explain my soluton as I've got a down vote.

With the styles set as shown above in css, now the following html div will show the image always fit width wise and will adjust hight aspect ratio to width. Thus image will scale to fit a bounding box as asked in the question.

<div class="boundingbox"><img src="image.jpg"/></div>

Are you looking to scale upwards but not downwards?

div {
    border: solid 1px green;
    width: 60px;
    height: 70px;
}

div img {
    width: 100%;
    height: 100%;
    min-height: 500px;
    min-width: 500px;
    outline: solid 1px red;
}

This however, does not lock aspect-ratio.


Today, just say object-fit: contain. Support is everything but IE: http://caniuse.com/#feat=object-fit


You can accomplish this with pure CSS and complete browser support, both for vertically-long and horizontally-long images at the same time.

Here's a snippet which works in Chrome, Firefox, and Safari (both using object-fit: scale-down, and without using it):

_x000D_
_x000D_
figure {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  width: 80px;_x000D_
  height: 80px;_x000D_
  border: 1px solid #aaa;_x000D_
}_x000D_
_x000D_
.container_image {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
  max-height: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
.container2_image2 {_x000D_
  width: 80px;_x000D_
  height: 80px;_x000D_
  object-fit: scale-down;_x000D_
  border: 1px solid #aaa;_x000D_
}
_x000D_
Without `object-fit: scale-down`:_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<figure class="container">_x000D_
  <img class="container_image" src="https://i.imgur.com/EQgexUd.jpg">_x000D_
</figure>_x000D_
_x000D_
<br>_x000D_
_x000D_
<figure class="container">_x000D_
  <img class="container_image" src="https://i.imgur.com/ptO8pGi.jpg">_x000D_
</figure>_x000D_
_x000D_
<br> Using `object-fit: scale-down`:_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<figure>_x000D_
  <img class="container2_image2" src="https://i.imgur.com/EQgexUd.jpg">_x000D_
</figure>_x000D_
_x000D_
<br>_x000D_
_x000D_
<figure>_x000D_
  <img class="container2_image2" src="https://i.imgur.com/ptO8pGi.jpg">_x000D_
</figure>
_x000D_
_x000D_
_x000D_


This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');
}

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!


Another solution without background image and without the need for a container (though the max sizes of the bounding box must be known):

img{
  max-height: 100px;
  max-width: 100px;
  width: auto;    /* These two are added only for clarity, */
  height: auto;   /* as the default is auto anyway */
}


If a container's use is required, then the max-width and max-height can be set to 100%:

img {
    max-height: 100%;
    max-width: 100%;
    width: auto; /* These two are added only for clarity, */
    height: auto; /* as the default is auto anyway */
}

div.container {
    width: 100px;
    height: 100px;
}

For this you would have something like:

<table>
    <tr>
        <td>Lorem</td>
        <td>Ipsum<br />dolor</td>
        <td>
            <div class="container"><img src="image5.png" /></div>
        </td>
    </tr>
</table>

html:

    <div class="container">
      <img class="flowerImg" src="flower.jpg">
    </div>

css:

.container{
  width: 100px;
  height: 100px;
}


.flowerImg{
  width: 100px;
  height: 100px;
  object-fit: cover;
  /*object-fit: contain;
  object-fit: scale-down;
  object-position: -10% 0;
  object-fit: none;
  object-fit: fill;*/
}

This example to stretch the image proportionally to fit the entire window. An improvisation to the above correct code is to add $( window ).resize(function(){});

function stretchImg(){
    $('div').each(function() {
      ($(this).height() > $(this).find('img').height()) 
        ? $(this).find('img').removeClass('fillwidth').addClass('fillheight')
        : '';
      ($(this).width() > $(this).find('img').width()) 
        ? $(this).find('img').removeClass('fillheight').addClass('fillwidth')
        : '';
    });
}
stretchImg();

$( window ).resize(function() {
    strechImg();
});

There are two if conditions. The first one keeps checking if the image height is less than the div and applies .fillheight class while the next checks for width and applies .fillwidth class. In both cases the other class is removed using .removeClass()

Here is the CSS

.fillwidth { 
   width: 100%;
   max-width: none;
   height: auto; 
}
.fillheight { 
   height: 100vh;
   max-width: none;
   width: auto; 
}

You can replace 100vh by 100% if you want to stretch the image with in a div. This example to stretch the image proportionally to fit the entire window.


I have used table to center image inside the box. It keeps aspect ratio and scales image in a way that is totally inside the box. If the image is smaller than the box then it is shown as it is in the center. Below code uses 40px width and 40px height box. (Not quite sure how well it works because I removed it from another more complex code and simplified it little bit)

_x000D_
_x000D_
.SmallThumbnailContainer {
  display: inline-block;
  position: relative;
  float: left;
  width: 40px;
  height: 40px;
  border: 1px solid #ccc;
  margin: 0px;
  padding: 0px;
}

.SmallThumbnailContainer {
  width: 40px;
  margin: 0px 10px 0px 0px;
}

.SmallThumbnailContainer tr {
  height: 40px;
  text-align: center;
}

.SmallThumbnailContainer tr td {
  vertical-align: middle;
  position: relative;
  width: 40px;
}

.SmallThumbnailContainer tr td img {
  overflow: hidden;
  max-height: 40px;
  max-width: 40px;
  vertical-align: middle;
  margin: -1px -1px 1px -1px;
}
_x000D_
<table class="SmallThumbnailContainer" cellpadding="0" cellspacing="0">
  <tr>
    <td>
      <img src="https://www.gravatar.com/avatar/bf7d39f4ed9c289feca7de38a0093250?s=32&d=identicon&r=PG" width="32" height="32" alt="OP's SO avatar image used as a sample jpg because it is hosted on SO, thus always available" />
    </td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Note: the native thumbnail size in this snippet is 32px x 32px, which is smaller than its 40px x 40px container. If the container is instead sized smaller than the thumbnail in any dimension, say 40px x 20px, the image flows outside the container in the dimensions that are smaller than the corresponding image dimension. The container is marked by a gray 1px border.


Thanks to CSS3 there is a solution !

The solution is to put the image as background-image and then set the background-size to contain.

HTML

<div class='bounding-box'>
</div>

CSS

.bounding-box {
  background-image: url(...);
  background-repeat: no-repeat;
  background-size: contain;
}

Test it here: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain

Full compatibility with latest browsers: http://caniuse.com/background-img-opts

To align the div in the center, you can use this variation:

.bounding-box {
  background-image: url(...);
  background-size: contain;
  position: absolute;
  background-position: center;
  background-repeat: no-repeat;
  height: 100%;
  width: 100%;
}

Here's a hackish solution I discovered:

#image {
    max-width: 10%;
    max-height: 10%;
    transform: scale(10);
}

This will enlarge the image tenfold, but restrict it to 10% of its final size - thus bounding it to the container.

Unlike the background-image solution, this will also work with <video> elements.

Interactive example:

_x000D_
_x000D_
 function step(timestamp) {
     var container = document.getElementById('container');
     timestamp /= 1000;
     container.style.left   = (200 + 100 * Math.sin(timestamp * 1.0)) + 'px';
     container.style.top    = (200 + 100 * Math.sin(timestamp * 1.1)) + 'px';
     container.style.width  = (500 + 500 * Math.sin(timestamp * 1.2)) + 'px';
     container.style.height = (500 + 500 * Math.sin(timestamp * 1.3)) + 'px';
     window.requestAnimationFrame(step);
 }

 window.requestAnimationFrame(step);
_x000D_
 #container {
     outline: 1px solid black;
     position: relative;
     background-color: red;
 }
 #image {
     display: block;
     max-width: 10%;
     max-height: 10%;
     transform-origin: 0 0;
     transform: scale(10);
 }
_x000D_
<div id="container">
    <img id="image" src="https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png">
</div>
_x000D_
_x000D_
_x000D_


The cleanest and simplest way to do this:

First some CSS:

div.image-wrapper {
    height: 230px; /* Suggestive number; pick your own height as desired */
    position: relative;
    overflow: hidden; /* This will do the magic */
    width: 300px; /* Pick an appropriate width as desired, unless you already use a grid, in that case use 100% */
}
img {
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
    height: auto;
}

The HTML:

<div class="image-wrapper">
  <img src="yourSource.jpg">
</div>

This should do the trick!


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 resize

Numpy Resize/Rescale Image AngularJS $watch window resize inside directive Input type "number" won't resize How can I make all images of different height and width the same via CSS? How to get full width in body element Rerender view on browser resize with React How to resize image automatically on browser width resize but keep same height? PHPExcel auto size column width Automatically resize images with browser size using CSS Change form size at runtime in C#

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?