Introduction
Centering elements vertically is a real pain in
CSS, and there is no straightforward solution for it. I will
attempt to give you some solutions to this common CSS
problem in following tutorial. All the code for the examples
used in this tutorial can be viewed by simply viewing the
source code for the page, or downloading the source .
Most beginners looking at a
CSS Property List would say, "Hey, the property
vertical-align looks like exactly what I am looking for to
vertically align my content." Well, if you ever tried to use
vertical-align to try to accomplish that task, you have
probably figured out that it does not do what you would
think it would. That is, vertical-align is NOT the
equivalent of a table tag's valign property. The CSS
vertical-align property aligns the element in relation to
its small outer container, or in geeky terms, in relation to
the inline container box (for more information check out
this page). Here is a example that illustrates
this behavior:
Hello,
here is some text that is vertically
aligned. |
[ here is
what the vertical-align property does ]
If you select the text you can see that it is in the
middle of the 'box for the text', the text is vertically
aligned. Unfortunately you can not use this property 'as is'
to vertically align an element, for example, that is inside
a div. As with almost everything on the web, there is a way
around this unwanted behavior. Values of this property have
slightly different meanings in the context of tables. Please
consult the section on table height algorithms for details.
This basically means that the property behaves differently
when applied to a table. Lets test it out by using this
property on a table:
This should be at the bottom |
|
[ testing
out the vertical align property on a table element ]
It works! Using vertical-align you can change the
vertical position of the content in a table. But, we are
modern web-developers and don't use ugly table based layouts
anymore, so what do we do? We emulate a table. Set the CSS
display property to table-cell, and you have CSS centering
in almost any element. Here is an example:
[ testing
out the vertical align property on a table element. Does not
work in IE ]
I have had the best luck using em's as a measurement when
trying to find the correct line-height value.
 |
Note |
I don't test on
browsers that weren't made that recently.
I've tested all the code in this tutorial in
the following browsers:
- FireFox 1.0
- Safari 1.2
- IE 6.0 SP1 (all
tricks work except the vertical-align
w/display:table-cell trick)
|
|
Conclusion
So this concludes my first shot at making a tutorial.
Hopefully you've found this information useful and will be
able to put to good use until support for CSS3 finally comes
around which will provide a much easier way to vertically
align content.
If you have any questions, or need
clarification on something, don't hesitate to ask in the
kirupa forums!