Center Page Vertically

Question:
How do I center a page in a window vertically, without using returns or tables?

Answer:
It’s easy to center the page horizontally–all you need to do is use the

tags. Centering it vertically is much more of a challenge. It can be done in IE4 with some work, but not with any Netscape browser.In order to center vertically, you need to know two things: the dimensions of the window you’re trying to center to, and the dimensions of the container. These values can be obtained using the clientWidth and clientHeight properties: the former on the document.body object, the latter on the division being used to hold the actual contents. I’ve written the VertCenter routine to actually do the resize.

Note the divLeft and divTop equations. The midpoint of a window or a div will be exactly half of the width. In order to determine where the left-hand side needs to go, I find the midpoint of the screen, move left and up (hence the negative sign) to the distance of the midpoint.

I pass a reference to the VertCenter function as an ID rather than a pointer because I wish to call it from outside of the DIV. Specifically, I need to catch the OnLoad and OnResize events for the page. This way, any time the screen is resized or reloaded, the div will center automatically.

Note that this doesn’t center the contents horizontally. If you wish to do that as well, you should place

within the encompassing DIV or LAYER.

	Untitled

Centering Verticallyis a little tougher

The center tag may not be the most elegant piece ofcode out there, but it does take care of handling the tediousjob of centering by hand. However, it doesn't support verticalcentering, making it exceedingly difficult to center an elementboth horizontally and vertically.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: