Unless otherwise stated, the content on this site is created with sharing authorization and is for non-commercial use. Please respect the fruits of your labor.
Original title: Vertical Centering in CSS
Subtitle: Yuhu's Definitive Solution with Unknown Height
Translation: forestgan
Although there is the vertical-align feature of CSS, it cannot effectively solve the vertical centering problem of unknown height (when there is text or image of unknown height in a DIV tag).
For standard browsers such as Mozilla, Opera, Safari, etc., you can set the display mode of the parent element to TABLE (display: table;) and the internal child elements to table-cell (display: table-cell). The vertical-align feature makes it vertically centered, but is not supported by non-standard browsers.
Non-standard browsers can only set the child element to be 50% from the top, and then put an element inside it with a distance of -50% from the top to offset it.
CSS
body {padding: 0; margin: 0;}
body,html{height: 100%;}
#outer {height: 100%; overflow: hidden; position: relative; width: 100%; background:ivory;}
#outer[id] {display: table; position: static;}
#middle {position: absolute; top: 50%;} /* for explorer only* /
#middle[id] {display: table-cell; vertical-align: middle; position: static;}
#inner {position: relative; top: -50%;width: 400px;margin: 0 auto;} /* for explorer only */
div.greenBorder {border: 1px solid green; background-color: ivory;}
XHTML
The advantage of the above CSS code is that there are no hacks and it uses the CSS2 selector #value[id] which is not supported by IE.
CSS2 selector #value[id] is equivalent to selector #value, but Internet Explorer does not support this type of selector. Likewise, .value[class] is equivalent to .value, which can only be read by standard browsers.
Test: Firefox1.5, Opera9.0, IE6.0, IE5.0 passed.