Proportional Video And Image Resizing

Fill a container with no white space

javascript,jquery,image resizing,aspect ratio

05/22/2014

This is a common need among front end designers and developers, but I feel like it can be hard to explain: You want to take an image or video or canvas, make it fill a container or browser window whose dimensions may change, keep its aspect ratio, but not leave any white space. It's easy to make something fill one of the dimensions, and leave a little white space on the other - just set the width or height to 100%, and the corresponding dimension to auto in CSS. But if you don't want any white space, it can be a bit confusing. What you really want to do is take the largest dimension, make your element resize to that dimension, and let the other dimension spill outside of the container (with overflow hidden). Here's a javascript (jQuery) equation for that:


//the element we are trying to fill
containerWidth = $('#container').width();
containerHeight = $('#container').height();

//the element we are filling it with
elementWidth = $('#element').width();
elementHeight = $('#element').height();

ratioDifference = elementWidth / containerWidth;

//find out how much we need to scale the element by in order to fill the container
//we are using scale to two decimal places over width and height for performance
if ((elementHeight / ratioDifference) < containerHeight){
    var scaleFactor = (containerHeight / elementHeight).toFixed(2)
}

else {
    var scaleFactor = (containerWidth / elementWidth).toFixed(2)
}

//set the css properties of the element. We are translating it by negative 50% to keep it centered
//(the css of the element should be set to left: 50%, top: 50%);
$('#element').css('transform', 'translate(-50%, -50%) scale(' + scaleFactor + ')');