Centring something horizontally and vertically with respect to the viewport using strict HTML4 (or a generic XML vocabulary) and CSS2 is not as obvious as it could be. In fact, to do this you have to use both fixed positioning and table layout.
First, mark up your content using structural HTML. For example, if you are going to be centering a header and a paragraph, your markup could look like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <html lang="en"> <head> <title>Demo 1</title> <style type="text/css"> /* we will put the stylesheet here */ </style> </head> <body> <div> <h1>Demonstration</h1> <p>This is the first demonstration</p> </div> </body> </html>
Note that we wrapped the markup you wish to centre in a
div
. This is required because we need two elements for
our CSS-fu, and we can't use the html
element because
the root element can't be positioned in CSS2.
The only block-level container in CSS2 that can be vertically
centred is a table cell, so we are going to need to make the inner
most container of your markup a table cell. The inner most container
is the div
element, and to make that a table cell we
just need the following CSS:
div { display: table-cell; }
To centre it, we use the vertical-align
property. Table cells automatically grow to fit their contents, so
we don't have to worry about height or width.
div { vertical-align: middle; }
Now we need to say what to center it in, and this has got to be a
table row, and in fact must be a table row which has the height of
the viewport. This is so that the cell is centred relative to the
right area. The div
's container is the
body
element, and to make it a table row fixed to the
viewport takes the following CSS:
body { display: table-row; position: fixed; top: 0; left: 0; right: 0; bottom: 0; }
We also need to make it horizontally centred (it's width will automatically size to the width of the cell), and to do that we use auto margins:
body { margin: auto; }
The net result is Demo 1. As far as I am aware, that is technically correct.
Unfortunately, it doesn't work in any browser as far as I am aware. Here is one that works in Mozilla. Here's one that works better in Mozilla.