Last active
August 29, 2015 14:01
-
-
Save JakeSidSmith/f80666f41505ab30a9a9 to your computer and use it in GitHub Desktop.
JQuery to make images cover their containing elements (cropped)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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