July 10 2012

Vertically and Horizontally align

I really wanted to use pure CSS to make this happen, but after some hours investigating, I resorted to Javascript (in the form of Jquery).

To use this code do the following:

1. Make sure that the parent element has position: relative or absolute.

2. Give the target image the class "supercenter"

3. Paste this code in your js file or inside a script tag:

[sourcecode language="javascript"]
$(document).ready(function() {
$("img.supercenter").each(function(){
var parent_height = $(this).parent().height();
var parent_width = $(this).parent().width();
var image_height = $(this).height();
var image_width = $(this).width();
var top_margin = (image_height)/-2;
var left_margin = (image_width)/-2;
$(this).css( 'margin-top' , top_margin);
$(this).css( 'margin-left' , left_margin);
$(this).css( 'left' , '50%');
$(this).css( 'top' , '50%');
$(this).css( 'position' , 'absolute');
});
});
[/sourcecode]