Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Resize image to fit container (See related posts)

Resizes an image to fit into its container, depending on whether the width or height is longer, yet keeping the aspect ratio. Copied from a comment on sitepoint.com.

ffunction resizeImgOO(el) 
{ 
        function imgRatio()
        { 
                return (el.height / el.width); 
        } 
        function holderRatio()
        { 
                return (el.offsetParent.offsetHeight / el.offsetParent.offsetWidth); 
        } 
        function fitToContainer()
        { 
                if(imgRatio>holderRatio) 
                { 
                        el.height = el.offsetParent.offsetHeight; 
                } 
                else 
                { 
                        el.width = el.offsetParent.offsetWidth;   
                } 
        }
        
        this.imgRatio = imgRatio; 
        this.holderRatio = holderRatio; 
        this.resize = fitToContainer; 
}
var img = new resizeImgOO(document.getElementById('yourImgId'));
img.resize();

You need to create an account or log in to post comments to this site.


Related Posts