Skip to content

Instantly share code, notes, and snippets.

@sowasred2012
Last active December 10, 2015 19:48
Show Gist options
  • Save sowasred2012/4484216 to your computer and use it in GitHub Desktop.
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).
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