Welcome to WebmasterWorld Guest from 54.227.5.198

Forum Moderators: incrediBILL

Message Too Old, No Replies

Vertically centered table or div - best way?

     

pelachrum

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

thanks

encyclo

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:

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

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">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Centered</title>
<style type="text/css">
#outer {
text-align:center;
position:absolute;
top:50%;
left:0;
width:100%;
height:1px;
background:blue;
}
#inner {
position: absolute;
top: -25px;
left: 50%;
margin-left:-125px;
width: 250px;
height: 50px;
border:1px solid black;
background:yellow;
}
</style>
</head>
<body>
<div id="outer">
<div id="inner">
This text box is centered on the screen
</div>
</div>
</body>
</html>

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.

pelachrum

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