So I have a collection of thumbnails in my app, which is the size of 200x200. Sometimes the original image doesn\'t have this ratio so I am planning to crop this image
I came up with my own solution and thought I would share it here in case anyone else found this thread. The background-size: cover solution is the easiest, but I needed something that would work in IE7 as well. Here's what I came up with using jQuery and CSS.
Note: My images were "profile" images and needed to be cropped to squares. Hence some of the function names.
jQuery:
cropProfileImage = function(pic){
var h = $(pic).height(),
w = $(pic).width();
if($(pic).parent('.profile-image-wrap').length === 0){
// wrap the image in a "cropping" div
$(pic).wrap('');
}
if(h > w ){
// pic is portrait
$(pic).addClass('portrait');
var m = -(((h/w) * 100)-100)/2; //math the negative margin
$(pic).css('margin-top', m + '%');
}else if(w > h){
// pic is landscape
$(pic).addClass('landscape');
var m = -(((w/h) * 100)-100)/2; //math the negative margin
$(pic).css('margin-left', m + '%');
}else {
// pic is square
$(pic).addClass('square');
}
}
// Call the function for the images you want to crop
cropProfileImage('img.profile-image');
CSS
.profile-image { visibility: hidden; } /* prevent a flash of giant image before the image is wrapped by jQuery */
.profile-image-wrap {
/* whatever the dimensions you want the "cropped" image to be */
height: 8em;
width: 8em;
overflow: hidden;
}
.profile-image-wrap img.square {
visibility: visible;
width: 100%;
}
.profile-image-wrap img.portrait {
visibility: visible;
width: 100%;
height: auto;
}
.profile-image-wrap img.landscape {
visibility: visible;
height: 100%;
width: auto;
}