Introduction
Vertical & Horizontal Centering of 'div' object
I wanted to center a div object vertically and horizontally within its parent div layer. I wanted to achieve this without using the HTML tables. The problem I was facing is that I did not know the height and width of the internal div object, because its content (long text) is dynamically generated. I tried the CSS property 'vertical-align: middle', but that does not seem to be able to solve my problem. I also tried many other ways using CSS but nothing help then I came up with this little piece of javascript that solve my problem easily.
The keystone of this solution is that the internal object is absolutely positioned in half of its parent's area height and then is moved up by half of its height. Similarly half of its parent's area width and then moved left by half of its width.
This simple javascript will dynamically align an internal div object in the middle of its parent layer. You do not need to know the height and width of the internal div object. You can fill in the content (typically long text) dynamically. This javascript works on IE6.0, Opera 9.23, FireFox2.0.0.8 and Netscape9.0b3.
Firefox and Netscape does not support 'pixel' property, so in order to work the codes on FF and N, you need to use parseInt() for getting the numeric portion of the size i.e. size without 'px'.
After download the codes replace the following lines:
//var a=Math.round(document.getElementById(Parent).style.pixelHeight/2);
//var x=Math.round(document.getElementById(Parent).style.pixelWidth/2);
with these one:
var a=Math.round(parseInt(document.getElementById(Parent).style.height)/2);
var vax=Math.round(parseInt(document.getElementById(Parent).style.width)/2);
This is a free javascript distributed in the hope that it will be useful but without any warranty.
Using the code
Simply pass the parent and child div objects to the javascript function, that's it. The child div object will be placed in the middle of the parent div object.
Run the attached sample file 'centering_div.aspx', which contains the complete example.
function AlignMiddle(Parent,Child)
{
document.getElementById(Child).innerHTML="Hello there, I am dynamically align in the middle using a Javascript."
h = document.getElementById(Child).offsetHeight;
var a=Math.round(parseInt(document.getElementById(Parent).style.height)/2);
var b=Math.round(h/2);
var c=a-b;
document.getElementById(Child).style.top=c+"px";
w = document.getElementById(Child).offsetWidth;
var x=Math.round(parseInt(document.getElementById(Parent).style.width)/2);
var y=Math.round(w/2);
var z=x-y;
document.getElementById(Child).style.left=z+"px";
}
History
Created by: Muhammad Shoaib
Created on: 10-10-2007