Welcome to WebmasterWorld Guest from

Forum Moderators: incrediBILL

Message Too Old, No Replies

Vertically centered table or div - best way?



4:29 am on Dec 18, 2005 (gmt 0)

10+ Year Member

what's the best method of vertically centering stuff on a page

For instance a table or a div (whichever would work for this) centered on a screen (horizontally and vertically) that remains as such when a window is resized



6:11 pm on Dec 18, 2005 (gmt 0)

WebmasterWorld Senior Member encyclo is a WebmasterWorld Top Contributor of All Time 10+ Year Member

There are two different methods, old-school and CSS. Firstly the old-school way with a table:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
<td width="100%" align="center">This text is centered on the screen</td>

Note that the above requires quirks mode in the browser and doesn't validate so you should not add a doctype. This method is perfect for a quick-and-dirty one-page implementation.

The second method is to use CSS:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<style type="text/css">
#outer {
#inner {
position: absolute;
top: -25px;
left: 50%;
width: 250px;
height: 50px;
border:1px solid black;
<div id="outer">
<div id="inner">
This text box is centered on the screen

This method centers a box (not an arbitrary piece of text) both horizontally and vertically. The basic idea is to have an outer container placed at 50% from the top with a 1px nominal height, and an inner container with a fixed height in pixels, a negative top position representing half of the declared height, and a negative left margin representing half of the declared width.

The CSS version is better when you have a more complex layout dependent on standards mode, but you may still need to use a table within the inner box - unfortunately as the difference between the two methods shows, vertical centering within the viewport is one of the weak points with CSS designs.


2:12 am on Dec 19, 2005 (gmt 0)

10+ Year Member

what I think is happening is making a document up to XHTML specs kills the CSS (I'm not even considering doing it as tables)
I've done something similar to what you described once but had it marked HTML 4.01 Transitional and it worked. The minute I swap the heading with XHTML, Firefox for instance plays nice but IE is not cooperating

Featured Threads

Hot Threads This Week

Hot Threads This Month