Vertical alignment in CSS has its challenges, with even CSS3 struggling to fully address the issue.
Fortunately, for fixed-height elements like yours, achieving vertical centering is possible by manipulating the top
and left
properties along with negative values for margin-top
and margin-left
using absolute positioning:
background: #FFFFFF;
width: 950px;
height: 630px;
top: 50%;
left: 50%;
margin: -315px 0 0 -425px; /*negative half of height and width*/
position: absolute;
Check out the Demo / View source code
Note that negative margins may behave unexpectedly on smaller screen resolutions compared to the size of the div
.
Another method involves using a table for centering content but is considered more of a hack. Utilizing the vertical-align:middle
property on a table cell mimics the effect of the old attribute valign="center"
. Here's how the HTML structure would look:
<table class="vcenter"><tr><td>
<div id="myDiv">This content is vertically centered</div>
</td></tr></table>
Accompanied by the following CSS rules:
.vcenter {
vertical-align: middle;
width: 100%;
height: 100%;
}
#myDiv {
background: #FFF;
width: 950px;
height: 630px;
margin: 0 auto;
}
html, body { height: 100%; }
See the Demo here / Source code available
This method boasts cross-browser compatibility, having been tested on IE6 and above, Firefox, Chrome, Opera, and Safari. While not specifically validated for mobile browsers, it should still function accordingly. Additionally, this approach avoids scrolling issues at lower resolutions and has been successfully used for centered modals on a live website.