faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 12 people (92%) answered Yes
Recently 7 of 8 people (88%) answered Yes

Entry

How do I center a HTML page element on the page?

Mar 19th, 2000 09:21
Martin Honnen,


Stuff your element into a positioned DIV or SPAN (that is really only 
needed for NN4, with IE4+ and NN6 you could directly apply positioning 
to the element you want to center), then get the window and the 
DIV/SPAN's dimensions and compute the center coordinates. At last move 
your element to the computed coordinates. The following contains a 
function 
  centerElement
that you pass an element id to center that element.
An example application is included.

<HTML>
<HEAD>
<STYLE>
.js { 
  color: white; 
  background-color: orange;
  font-size: 18pt; 
  text-decoration: none; 
}
#aSpan { position: absolute; visibility: hidden; }
</STYLE>
<SCRIPT>
function centerElement (id) {
  var el, windowWidth, windowHeight, elWidth, elHeight, cx, cy;
  if (document.layers) {
    el = document[id];
    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;
    elWidth = el.document.width;
    elHeight = el.document.height;
  }
  else if (document.all) {
    el = document.all[id];
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
    elWidth = el.offsetWidth;
    elHeight = el.offsetHeight;
  }
  else if (document.getElementById) {
    el = document.getElementById(id);
    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;
    elWidth = el.offsetWidth;
    elHeight = el.offsetHeight;
  }
  cx = Math.floor((windowWidth - elWidth) / 2);
  cy = Math.floor((windowHeight - elHeight) / 2);
  if (document.layers) {
    el.left = cx;
    el.top = cy;
    el.visibility = 'show';
  }
  else if (document.all || document.getElementById) {
    el.style.left = cx + 'px';
    el.style.top = cy + 'px';
    el.style.visibility = 'visible';
  }
}
function init () {
  centerElement('aSpan');
}
</SCRIPT>


</HEAD>
<BODY ONLOAD="init();">
<SPAN ID="aSpan">
<A HREF="JavaScript.FAQTs.com" CLASS="js">
JavaScript.FAQTs.com
</A>
</SPAN>
</BODY>
</HTML>


At the time of writing NN6's ability to return the computed dimensions 
of a SPAN seem to be buggy so the above example is not working 
correctly with NN6.