Til den downe er her et copy-paste eksempel på hvordan man centrer og placerer forskellige lag i forhold til midten. Eksemplet er med udgangspunkt i ovennævnte URL:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html>
<head>
<title>Horisontal og Vertikal Centrering via CSS og JS</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
body {
margin:0px; padding:0px;
}
dt {font-weight:bold;}
#center {
padding:0px;
width:1px;
height:1px;
position:absolute;
}
</style>
<script type="text/javascript">
function posCenter() {
if (self.innerWidth)
{
frameWidth = self.innerWidth;
frameHeight = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth)
{
frameWidth = document.documentElement.clientWidth;
frameHeight = document.documentElement.clientHeight;
}
else if (document.body)
{
frameWidth = document.body.clientWidth;
frameHeight = document.body.clientHeight;
}
oCenter = document.getElementById('center');
oCenterWidth = oCenter.offsetWidth;
oCenterHeight = oCenter.offsetHeight;
nW=Math.round((frameWidth/2)-(oCenterWidth/2));
nH=Math.round((frameHeight/2)-(oCenterHeight/2));
oCenter.style.left=nW+'px';
oCenter.style.top=nH+'px';
}
isOpera = (window.opera);
var origWidth,origHeight;
function handlerLoad() {
if (isOpera) {
origWidth = this.innerWidth;
origHeight = this.innerHeight;
handlerResize();
}
posCenter();
}
function handlerResize() {
if (this.innerWidth != origWidth
||
this.innerHeight != origHeight) location.reload();
if (isOpera) setTimeout('handlerResize()',500);
posCenter();
}
window.onresize = handlerResize
window.onload = handlerLoad
</script>
</head>
<body>
<div id="center"><b>.</b>
<div style="position:absolute; top:0; left:-50; width: 100px;">(0,-50)</div>
<div style="position:absolute; top:50; left:-50; width: 100px;">(50,-50)</div>
<div style="position:absolute; top:200; left:100; width: 100px;">(200,100)</div>
</div>
</body>
</html>
mvh