Use PHP to Center an Image in a DIV

I have created a way to always center an image in a DIV container. (providing the image is smaller than the container). This has been a thorn in my side as CSS is not my strongest skill. So here is the concept. Have a container DIV that has a fixed width and height. Then use the GD Library installed with PHP to get the image size that is being displayed inside the DIV. Then subtract the image height from the container height and divide by two. You can do the same for the height. Here is the HTML and CSS
<style type="text/css">

#image-container { width: 450px; height: 450px; }

</style>

<div id="image-container">
<div style="margin-top: <?php echo $margin_top; ?>px; margin-left: <?php echo $margin_left; ?>px;">
<img src="/path/to/your/image.jpg">
</div>
</div>

Here is the PHP that fills in the margin top and left
<?php
$image = "/server/path/to/image.jpg";
// example "/home/matt/matthewaprice.com/image.jpg"
$size = getimagesize($image);
$width = "450";
$height = "450";

$margin_top = ($width - $size[0]) /2;
$margin_left = ($height - $size[1]) /2;
?>

Post a comment





Real Time Web Analytics ^