JavaScript technique to center image in div for flexible webdesign

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


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

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.


window.onresize = function() {
$( "li img" ).each(function( index ) {
DrawCentered(this);
});
}

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
}
else
{
gScaledHeight = iHeight*(cWidth/iWidth);

gScale = gScaledHeight/iHeight;

gScaledWidth = gScale*iWidth;

gOffX = 0;
gOffY = (cHeight-gScaledHeight)/2.0;
}

$(im).css("width",gScaledWidth);
$(im).css("height",gScaledHeight);
$(im).css("padding-top",gOffY+"px");
$(im).css("padding-left",gOffX+"px");
}