Skip to content

Instantly share code, notes, and snippets.

@johnpolacek
Last active February 6, 2018 16:47
Show Gist options
  • Save johnpolacek/5962548 to your computer and use it in GitHub Desktop.
Save johnpolacek/5962548 to your computer and use it in GitHub Desktop.
The jQuery plugin for making an image fill its container (and be centered) - see http://johnpolacek.github.io/imagefill.js/
/**
* imageFill.js
* Author & copyright (c) 2013: John Polacek
* Dual MIT & GPL license
*
* This gist is out of date now. I've turned this into a proper Github project at http://johnpolacek.github.io/imagefill.js/
*
*/
;(function($) {
$.fn.imageFill = function() {
var $container = this,
$img = $container.find('img').css({'position':'absolute'}),
imageAspect = 1/1;
// make sure container isn't position:static
var containerPos = $container.css('position');
$container.css({'overflow':'hidden','position':(containerPos === 'static') ? 'relative' : containerPos});
// wait for image to load, then fit it inside the container
$container.imagesLoaded().done(function($img) {
imageAspect = $img.width() / $img.height();
fitImage($img);
});
function fitImage() {
var containerW = $container.width();
var containerH = $container.height();
var containerAspect = containerW/containerH;
if (containerAspect < imageAspect) {
// taller
$img.css({
width: 'auto',
height: containerH,
top:0,
left:-(containerH*imageAspect-containerW)/2
});
} else {
// wider
$img.css({
width: containerW,
height: 'auto',
top:-(containerW/imageAspect-containerH)/2,
left:0
});
}
}
$(window).smartresize(function(){
fitImage();
});
};
}(jQuery));
@johnpolacek
Copy link
Author

This gist is out of date now. I've turned this into a proper Github project at http://johnpolacek.github.io/imagefill.js/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment