Resizing and cropping an image in HTML5 and css


My requirements -

  1. A random image gets displayed inside div/canvas
  2. Image height should get adjusted to parent height
  3. Image width should get re-sized proportionately (with height)
  4. If image width is more than parent width, crop from left and right equally

I have achieved this with java script. Jsfiddle is at You can resize the output window to see how it is working.

However I feel that I am doing it tedious way and there is something very simple in CSS and/or jQuery. could you please help me with pure css (preferably)?

I am attaching java script here as well -

var strDataURI;
window.onresize = function(event) {
function displayBackground(bChangeImage)
 var appWidth = window.innerWidth;
 var appHeight = window.innerHeight;
 if (bChangeImage)
   var suffix_array = ["_california","_easter","_eiffel","_hk","_taj"];
   var ran = Math.floor((Math.random()*5)+1);
   ran = ran - 1;
   //ran = 3;
   strDataURI = ""+suffix_array[ran]+".jpg";
 var myCanvas = document.getElementById('canvas');
 var ctx = myCanvas.getContext('2d');
 var img = new Image;
 img.onload = function(){
  ctx.canvas.width  = appWidth;
  ctx.canvas.height = appHeight;
  var hFraction = appHeight / img.naturalHeight;
  var displayWidth = img.naturalWidth*hFraction;
  mrgLeft = (appWidth - displayWidth)/2;
  mrgTop = (appHeight - img.naturalHeight)/2;
  ctx.drawImage(img,mrgLeft,0, displayWidth, appHeight);
  //blurMargin = 20;
  //stackBlurCanvasRGB( "canvas", blurMargin, blurMargin, appWidth-blurMargin*2, appHeight-blurMargin*2, 6 );
 img.src = strDataURI;
Problem courtesy of: Prasoon


This should do the trick :



<div id="canvasHolder">


    background: white url( no-repeat center center;
    background-size: auto 100% ;
Solution courtesy of: web-tiki


To have the height of a background image always keep to 100% of the containing element and the width automatically scale, keeping the ratio, just set the background-size to "auto 100%" so that the width is set to auto and the height to 100%. The width will scale proportionately while the height always stays at 100% of the containing element's height.

The centering provides the automatic cropping left and right.


  <div class="container">       


.container {
  background-image: url(;
  background-size: auto 100%;
  background-repeat: no-repeat;
  background-position: center;
  height: 300px;

See my jsBiin demo here. Change the height of the container in the CSS to see the image automatically scale proportionately.

Discussion courtesy of: guymid

This recipe can be found in it's original form on Stack Over Flow.