ADAM'S WEB PRESENCE

3 October 2008

Centering and Scaling an Image on a Web Page

Filed under: General — adam @ 10:34 am

I want a web page which displays a single image. The image is to be scaled so it is as large as possible within the browser but without losing it’s aspect ratio.

I also want it to be centred (or centered if you are American).

After spending literally hours trying to do this with CSS and scads of nested div tags, I have decided it is not possible to do it this way. The alternative was to use Javascript to compute the size and position of the image.

Here is the final code which works on IE and Firefox:

<html>
<head>
<script>
function scaleAndCenter(id)
{
 img = document.getElementById(id);
 img.style.position = "absolute";

 if(img.width / document.body.clientWidth > img.height / document.body.clientHeight)
 {
  img.style.width = "100%";
  img.style.top   = (document.body.clientHeight - img.height) / 2;
 }
 else
 {
  img.style.height = "100%";
  img.style.left   = (document.body.clientWidth - img.width) / 2;
 }
}
</script>
</head>
<body style="margin: 0; background: black;">
<img id="image" src="myimage.jpeg" onload="scaleAndCenter(this.id)" />
</body>
</html>

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment


Powered by WordPress