jQuery resize to aspect ratio

Here’s a useful function that might do what you want:

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;
        }
        var margin_top  = (parentHeight - newHeight) / 2;
        var margin_left = (parentWidth  - newWidth ) / 2;

        $(this).css({'margin-top' :margin_top  + 'px',
                     'margin-left':margin_left + 'px',
                     'height'     :newHeight   + 'px',
                     'width'      :newWidth    + 'px'});
    });
};

Basically, it grabs an element, centers it within the parent, then stretches it to fit such that none of the parent’s background is visible, while maintaining the aspect ratio.

Then again, this might not be what you want to do.

Leave a Comment