[css] How can I fill a div with an image while keeping it proportional?

I found this thread — How do you stretch an image to fill a <div> while keeping the image's aspect-ratio? — that is not entirely the thing that I want.

I have a div with a certain size and an image inside of it. I want to always fill-out the div with the image regardless if the image is landscape or portrait. And it doesn't matter if the image is cut-off (the div itself has overflow hidden).

So if the image is portrait I want the width to be 100% and the height:auto so it stays in proportion. If the image is landscape I want the height to be 100% and the width to beauto`. Sounds complicated right?

<div class="container">
   <img src="some-image.jpg" alt="Could be portrait or landscape"/>
</div>

Since I don't know how to do it I simply created a quick image of what I mean. I can't even properly describe it.

enter image description here

So, I guess I'm not the first one asking this. However I couldn't really find a solution to this. Maybe there is some new CSS3 way of doing this - I'm thinking of flex-box. Any idea? Maybe it's even easier than I expect it to be?

This question is related to css image positioning

The answer is


Just fix the height of the image & provide width = auto

img{
    height: 95vh;
    width: auto;
}

You can achieve this using css flex properties. Please see the code below

_x000D_
_x000D_
.img-container {_x000D_
  border: 2px solid red;_x000D_
  justify-content: center;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  overflow: hidden;_x000D_
  _x000D_
}_x000D_
.img-container .img-to-fit {_x000D_
  flex: 1;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="img-container">_x000D_
  <img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_


An old question but deserves an update as now there is a way.

The correct CSS based answer is to use object-fit: cover, which works like background-size: cover. Positioning would be taken care of by object-position attribute, which defaults to centering.

But there is no support for it in any IE / Edge browsers, or Android < 4.4.4. Also, object-position is not supported by Safari, iOS or OSX. Polyfills do exist, object-fit-images seems to give best support.

For more details on how the property works, see CSS Tricks article on object-fit for explanation and demo.


The only way I achieved the "best case" scenario described, was putting the image as a background:

<div class="container"></div>?
.container {
    width: 150px;
    height: 100px;
    background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
}?

Here is an answer with support to IE using object-fit so you won't lose ratio

Using a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

_x000D_
_x000D_
//ES6 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('img[data-object-fit]').forEach(image => {
      (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
      image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
    })
  })
}

//ES5 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', function() {
    Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
      (image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
      image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
    }));
  });
}
_x000D_
img {
  display: inline-flex;
  width: 175px;
  height: 175px;
  margin-right: 10px;
  border: 1px solid red
}


/*for browsers which support object fit */

[data-object-fit='cover'] {
  object-fit: cover
}

[data-object-fit='contain'] {
  object-fit: contain
}
_x000D_
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />
_x000D_
_x000D_
_x000D_


Note: There are also a few object-fit polyfills out there that will make object-fit work.

Here are a few examples:


Try this:

img {
  position: relative;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  transform: translateX(-50%);
}

Hope this helps


It's a bit late but I just had the same problem and finally solved it with the help of another stackoverflow post (https://stackoverflow.com/a/29103071).

img {
   object-fit: cover;
   width: 50px;
   height: 100px;
}

Hope this still helps somebody.

Ps: Also works together with max-height, max-width, min-width and min-height css properties. It's espacially handy with using lenght units like 100% or 100vh/100vw to fill the container or the whole browser window.


If I correctly understand what you want, you may leave the width and height attributes off the image to maintain aspect ratio and use flexbox to do the centering for you.

_x000D_
_x000D_
.fill {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden
}
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}
_x000D_
<div class="fill">
    <img src="https://picsum.photos/id/237/320/240" alt="" />
</div>
_x000D_
_x000D_
_x000D_

JSFiddle here

I tested this successfully in IE9, Chrome 31, and Opera 18. But no other browsers were tested. As always you must consider your particular support requirements.


_x000D_
_x000D_
.image-wrapper{_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    border: 1px solid #ddd;_x000D_
}_x000D_
.image-wrapper img {_x000D_
    object-fit: contain;_x000D_
    min-width: 100%;_x000D_
    min-height: 100%;_x000D_
    width: auto;_x000D_
    height: auto;_x000D_
    max-width: 100%;_x000D_
    max-height: 100%;_x000D_
}
_x000D_
<div class="image-wrapper">_x000D_
  <img src="">_x000D_
</div>
_x000D_
_x000D_
_x000D_


All answers below have fixed width and height, which makes solution "not responsive".

To achieve the result but keep image responsive I used following:

  1. Inside container place a transparent gif image with desired proportion
  2. Give an image tag inline css background with image you want to resize and crop

HTML:

<div class="container">
    <img style="background-image: url("https://i.imgur.com/XOmNCwY.jpg");" src="img/blank.gif">
</div> 


.container img{
   width: 100%;
   height: auto;
   background-size: cover;
   background-repeat: no-repeat;
   background-position: center;
}?

Here you have my working example. I have used a trick that is setting the image as background of the div container with background-size:cover and background-position:center center

I have placed the image with width:100% and opacity:0 making it invisible. Note that I am showing my image only because I have an special interest on calling the child click event.

Please note that altought I am ussing angular it is completely irrelevant.

<div class="foto-item" ng-style="{'background-image':'url('+foto.path+')'}">
    <img class="materialboxed" ng-class="foto.picid" ng-src="{{foto.path}}" style="opacity: 0;filter: alpha(opacity=0);" width="100%" onclick="$('.materialboxed')/>
 </div>
<style>
.foto-item {
height: 75% !important;
width: 100%;
position: absolute;
top: 0;
left: 0;
overflow:hidden;
background-size: cover;
background-position: center center;
}
</style>

The result is the one that you define as optimal in all cases


Consider using background-size: cover (IE9+) in conjunction with background-image. For IE8-, there is a polyfill.


This should do it:

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

The CSS object-fit: cover and object-position: left center property values now address this issue.


You can use div to achieve this. without img tag :) hope this helps.

_x000D_
_x000D_
.img{_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
 background-image:url('http://www.mandalas.com/mandala/htdocs/images/Lrg_image_Pages/Flowers/Large_Orange_Lotus_8.jpg');_x000D_
 background-repeat:no-repeat;_x000D_
 background-position:center center;_x000D_
 border:1px solid red;_x000D_
 background-size:cover;_x000D_
}_x000D_
.img1{_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
 background-image:url('https://images.freeimages.com/images/large-previews/9a4/large-pumpkin-1387927.jpg');_x000D_
 background-repeat:no-repeat;_x000D_
 background-position:center center;_x000D_
 border:1px solid red;_x000D_
 background-size:cover;_x000D_
}
_x000D_
<div class="img"> _x000D_
</div>_x000D_
<div class="img1"> _x000D_
</div>
_x000D_
_x000D_
_x000D_


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 positioning

jQuery position DIV fixed at top on scroll CSS transition effect makes image blurry / moves image 1px, in Chrome? How can I fill a div with an image while keeping it proportional? In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document? sizing div based on window width Make div stay at bottom of page's content all the time even when there are scrollbars How to position the div popup dialog to the center of browser screen? How do I center an SVG in a div? CSS: Position text in the middle of the page Stopping fixed position scrolling at a certain point?