Dowemo
0 0 0 0


Question:

<body>
    <div style="position:absolute; height:100%; width:100%;">
        <h1 style="text-align:center;">Text</h1>
    </div>
</body>

How can I vertically center the h1 tag inside of the div tag, no matter how tall the div element is? i.e. If the user changes his browser height, I want the h1 to vertically align in the center, according to the new height.

Thanks.


Best Answer:


There's a cross (desktop) browser solution to do this with CSS2 + CSS3 and without any Javascript.

Works in

  • IE5+
  • Gecko's (Mozilla, Firefox, Netscape 7)
  • Opera 7+
  • Konqueror 3+
  • Webkit Browsers (Safari, Google Chrome)
  • and a lot more (Mobile browsers not tested)

Documentation: Vertical Centering in CSS Definitive Solution with Unknown Height:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Clean jsFiddle Example: http://jsfiddle.net/WYgsP/HTML

<div class="outerBox">
    <div class="helper">
        <div class="boxWithUnknownHeight">
            any text<br>
            any height<br>
            any content, for example generated from DB<br>
            everything is vertically centered
        </div>
    </div>
</div>​

CSS

.outerBox {
    display: table;
    height: 400px;
    #position: relative; /* ie hack */
    overflow: hidden;
    border: 1px solid red;
}
.helper {
    #position: absolute; /* ie hack */
    #top: 50%; /* ie hack */
    display: table-cell;
    vertical-align: middle;
}
.boxWithUnknownHeight {
    #position: relative; /* ie hack */
    #top: -50%;
    border: 1px solid green
}​

It works, even if i add text and line-breaks through Firebug etc.
To keep your CSS clean from invalid CSS-Hacks, I'll recommend you to use conditional comments for it and create a separate CSS with the browser specific Code.

How vertical centering with unknown height exactly works and why: Detailed description

Other solutions with display: table and or display: table-cell and or absolute positioning here.




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs