Original article title: Vertical Centering in CSS
Subtitle: Yuhu's Definitive Solution with Unknown Height
Despite the vertical-align feature of CSS, it cannot effectively solve the vertical center problem of unknown height (in the case of text or images with unknown heights in a DIV label ).
Standard browsers such as Mozilla, Opera, and Safari ., you can set the display mode of parent-level elements to TABLE (display: table;) and the internal sub-elements to table-cell (display: table-cell ), vertical-align features are used to center vertices vertically, but non-standard browsers do not.
Non-standard browsers can only set the header to 50% in the child element, and then set another element to offset from the top to 50%.
CSS
The code is as follows: |
Copy code |
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 <Div id = "outer"> <Div id = "middle"> <Div id = "inner" class = "greenBorder"> </Div> </Div> </Div>
|
The advantage of the above CSS code is that there is no hacks and the CSS2 selector # value [id] that is not supported by IE is used.
CSS2 selector # value [id] is equivalent to selector # value, but Internet Explorer does not support this type of selector. Similarly,. value [class] is equivalent to. value, which can only be understood by standard browsers.
Test: Firefox1.5, Opera9.0, IE6.0, and IE5.0 pass.