Back in the day, when TABLES ruled the world, getting a layout compleely centered in the page was relatively easy: you’d just insert a one-cell table, align that table to the center both horisontally and vertically, and then you’d insert yet anothr table in that cell. That was it, plain and simple. But this would never work in NS, for the simple reason that NS would only observe the first table’s height – the rest of the tables’ heights being totally disregarded. Well, that was back in the day, when not only did people know what NS was (Netscape, for younger kids), but NS was the buzz-word of the day and everybody used it. Not anymore.
But the problem stays. Why? Because verical-aligning is only specific to certain HTML elements, and DIV isn’t one of them. So what then?
Well… it depends. You have not one, but two solutions, depending wheather you want your DIV to have a fixed height, or you want it to have a height relative to the height of the page. In either case, the basic principle is that your DIV must be placed into a context clearly defined position-wise, be it relative or absolute. Let’s take them one at a time…
1. Vertically centered DIV with the height relative to the height of the page.…
Simple
You set the din in the CSS, with the following parameters:
position: absolute; height: x%; top: ((100-x)/2)%;

Well, what I just wrote is an EXAMPLE, not to be taken literally, but to be interpreted. Don’t just copy-paste, cuz it won’t work. See it “translated” into usable code, in this example:
position: absolute; height: 40%; top: 30%;
If you have any questions, please leave a comment and we’ll sort them out
1. Vertically centered DIV with fixed height.
This one may look trickyer… but it’s doable. Before anything, let’s create a “dummy” div, and define it like so::
.dummy {position: absolute; top: 50%;}
Clearly, this div will sit exactly in the vertical middle of the page. Step 2 is to create, inside this dummy div, the div that we really care about. Let’s say it will have the height “X”. The CSS parameters will look like this:
position: absolute; height: Xpx; top: (-X/2)px;

Again, this is just an example of a formula. Translated in a real-life example, it would look something like this:
position: absolute; height: 300px; top: -150px;
Problem solved!
Note 1: For whoever doesn’t quite grasp yet what’s going on with position:absolute and what it involves, I strongly recommend the post Elements positioned ABSOLUTE in a RELATIVE context.
Note 2: For who has problems with horisontal alignment or with widths, read this: Horisontally centered DIVs: look out for MARGINs!.
Final Note: The parameters given in the examples above represent a bare minimum necessary for the functioning of these examples. You’re, obviously, free to add up as many extra parameters as you see fit, starting with the common width and going up the ladder to the baddest meanest hacks you know.

0 Responses to “DIV vertically centered in the page – no tables”
Leave a Reply