Last active
December 10, 2015 19:48
-
-
Save sowasred2012/4484216 to your computer and use it in GitHub Desktop.
This was written by Eric (http://stackoverflow.com/users/102441/eric), in response to this question on SO: http://stackoverflow.com/questions/1682495/jquery-resize-to-aspect-ratio Resizes images to fit their parent, blowing it out of the sides if necessary to completely fill any white space (and the parent container is set to overflow:hidden).
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
jQuery.fn.fitToParent = function() | |
{ | |
this.each(function() | |
{ | |
var width = $(this).width(); | |
var height = $(this).height(); | |
var parentWidth = $(this).parent().width(); | |
var parentHeight = $(this).parent().height(); | |
if(width/parentWidth < height/parentHeight) | |
{ | |
newWidth = parentWidth; | |
newHeight = newWidth/width*height; | |
} | |
else | |
{ | |
newHeight = parentHeight; | |
newWidth = newHeight/height*width; | |
} | |
margin_top = (parentHeight - newHeight) / 2; | |
margin_left = (parentWidth - newWidth ) / 2; | |
$(this).css({'margin-top' :margin_top + 'px', | |
'margin-left':margin_left + 'px', | |
'height' :newHeight + 'px', | |
'width' :newWidth + 'px'}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment