Skip to content

Instantly share code, notes, and snippets.

@JakeSidSmith
Last active August 29, 2015 14:01
Show Gist options
  • Save JakeSidSmith/f80666f41505ab30a9a9 to your computer and use it in GitHub Desktop.
Save JakeSidSmith/f80666f41505ab30a9a9 to your computer and use it in GitHub Desktop.
JQuery to make images cover their containing elements (cropped)
$(document).ready(function () {
// Find thumbnail containers
$('.thumbContainer').each(function () {
// Get current thumbnail container
var thumb = $(this);
// Get current thumbnail image
var img = thumb.children('img');
// Calculate image ratio
var ratio = img.innerWidth() / img.innerHeight();
var newW, newH;
// Calculate new width & height
if (ratio >= 1) {
newH = thumb.outerHeight();
newW = newH * ratio;
} else {
newW = thumb.outerWidth();
newH = newW / ratio;
}
// Apply new width & height
img.width(newW);
img.height(newH);
// Calculate and apply offsets
img.css('top', (thumb.innerHeight() - newH) / 2);
img.css('left', (thumb.innerWidth() - newW) / 2);
});
});
.parent {
position: relative;
overflow: hidden;
}
.parent img {
position: absolute;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment