How to center images in DIVS for flexible web designs

Javascript technique to center image in DIV for flexible webdesign

First make sure the DrawCentered function is called after the image loads as below

      <img src="exampleimage.png" onload="DrawCentered(this);"/>

Then add the resizing code below to your html file (for example: in document load function). The images will allways be centered within the container DIV, regardless of image size or page width. For an example of images within the Woothemes flexsider, check out altona-webdesign

    window.onresize = function() { 
            $( "li img" ).each(function( index ) {

    function DrawCentered(im)
	var gScaledHeight, gScaledWidth;

        var iWidth=im.width, iHeight=im.height; 
        var cWidth=$(im).closest("div").width(); 
        var cHeight=$(im).closest("div").height();

	gScaledWidth = iWidth*(cHeight/iHeight);
	// see which is the image's biggest dimension
	if( cWidth > gScaledWidth ) //scale cHeight
		// ratio of new to old cWidth
		gScale = gScaledWidth/iWidth;
		gScaledHeight = gScale*iHeight;
		gOffY = 0;
		gOffX = (cWidth-gScaledWidth)/2.0
		gScaledHeight = iHeight*(cWidth/iWidth);
		gScale = gScaledHeight/iHeight;
		gScaledWidth = gScale*iWidth;
		gOffX = 0;
		gOffY = (cHeight-gScaledHeight)/2.0;

Apr 9, 2014 Category: javascript Posted by: dave