Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Last active December 21, 2015 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willbroderick/83b753147565d3a9927c to your computer and use it in GitHub Desktop.
Save willbroderick/83b753147565d3a9927c to your computer and use it in GitHub Desktop.
Wraps an image with a fixed-ratio div and scales/translates the image to fill. Uses % CSS so no resize events needed.
/// Crop and scale images to a specific ratio
$.fn.cropImageToRatio = function(params){
//params
var params = $.extend({
ratio: 4/3,
wrapper: '<div/>'
}, params);
//loop all images
return $(this).each(function(){
//only allow init once
if(typeof $(this).data('imgratio') == 'undefined') {
//save ratios
var imgRatio = $(this).width() / $(this).height(),
viewRatio = params.ratio;
//padding-top is calculated from container width
var padScalar = $(this).width() / $(this).parent().width();
$(this).data('imgratio', imgRatio);
$(this).css({ //img css
position: 'absolute',
maxWidth: 'none',
maxHeight: 'none'
}).wrap(params.wrapper).parent().css({ //viewport css
height: 0,
paddingTop: 100 / params.ratio * padScalar + '%',
overflow: 'hidden',
position: 'relative'
});
//set image size and offset
if(imgRatio < viewRatio) {
$(this).css({
top: - (viewRatio / (imgRatio * 2) - 0.5) * 100 + '%',
left: 0,
width: '100%',
height: 'auto'
});
} else {
$(this).css({
top: 0,
left: - (imgRatio / (viewRatio * 2) - 0.5) * 100 + '%',
width: 'auto',
height: '100%'
});
}
}
});
};
//Example use.
//note: images must be loaded first, and it must be called directly on img tags
$(window).on('load', function(){
$('.article .header-image img').cropImageToRatio({ ratio: 16/9 });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment