Centering vertically and Horizontally with the DOM
Posted: Thu, 2003-09-11 00:25
function centerLayer(layer){
var h=0;
var w=0;
if(document.compatMode == "CSS1Compat"){
//IE Standard mode
w =document.body.parentNode.clientWidth;
h =document.body.parentNode.clientHeight;
}else{
//IE Quirks Mode
w =document.body.clientWidth;
h =document.body.clientHeight;
}
if(w==0){
//Netscape
w = window.innerWidth;
h = window.innerHeight;
}
var thelayer=document.getElementById(layer);
var thelayerw = parseInt(thelayer.style.width); //current width
var thelayerh = parseInt(thelayer.style.height); //current Height
var newleft= parseInt(((w/2) - (thelayerw/2)));
var newtop= parseInt(((h/2) - (thelayerh/2 )));
var newleft= ((w/2) - (thelayerw/2));
var newtop= ((h/2) - (thelayerh/2 ));
//Check if value is less then 0
if(newleft < 0){
newleft=0;
}
if(newtop < 0){
newtop=0;
}
thelayer.style.left=newleft+"px";
thelayer.style.top=newtop+"px";
}
Usage
<body onload="javascript:centerLayer('mylayer');">
<div id="mylayer" style="position:absolute; top:0; left:0; width:200px; height:100px; background-color:red;">this div should be centered</div>Your question may have already been answered, search and read before you ask.


Moderator
Posts: 2772
Joined: 2003-03-12
Location: Brisbane
Centering vertically and Horizontally with the DOM
Posted: Tue, 2003-09-16 20:59
I made some corrections to the above script.
Removed the quotes around "layer" in
var thelayer=document.getElementById(layer);Replaced isNaN function with parseInt to ensure we had numbers.
You should also note:
Specify styles inline
egposition the div or layer absolutely
specify initial top and left values
specify height and width values
use pixel values
<div id="layer" style="position:absolute; top:0px; left:0px; width:200px; height:100px; border:solid 1px red;">This should be centered</div>Your question may have already been answered, search and read before you ask.