This is one of the more common questions I see when it comes to CSS. It’s definitely not as straight forward as the valign=”middle” align=”center” that we used to use in tables (and still do). All the while, folks are doing their best to move completely out of tables and accomplish everything they used to do with an all CSS layout. Something that would be seemingly simple is actually not very straightforward at all. Here’s the method (demo).
CSS Breakdown
height:100%;
margin:0;
padding:0;
}
body {
background-color:#ccc;
text-align:center;
min-width:720px;
min-height:420px;
}
#head {
margin:-210px 0 0 0; /* half the minimum height*/
width:100%;
float:left;
height:50%;
}
#wrapper {
margin:0 auto;
width:718px; /* width minus 2px for the border */
height:418px; /* height minus 2px for the border */
border:1px solid white;
background:#333;
overflow:auto;
text-align:left;
clear:both;
}
h1 { /* none of the code in this tag is relevant to the formatting */
color:#fff;
margin:0;
padding:10px;
}
The HTML
<div id=”head”></div>
<div id=”wrapper”>
<h1>Insert your text</h1>
</div>
Now that we’ve got it working on a full page layout, lets see what we can do with an element within the page.
CSS Breakdown
color:#fff;
margin:0 5px;
padding:5px;
border:1px solid #ddd;
}
.vc {
border:1px solid #eee;
margin:10px;
display: table;
height: 300px;
background-color:#444;
position:static;
overflow:hidden;
}
.vwrap {
display: table-cell;
vertical-align: middle;
position: relative;
text-align:center;
margin:0 auto;
top: 50%;
}
</style>
<!–[if IE]>
<style type=”text/css”>
.vc {
position:relative;
}
.vwrap {
position: absolute;
top: 50%;
}
.vcontent {
width:100%;
margin:0 auto;
position:relative;
top: -50%;
}
</style>
<![endif]–>
The HTML
<div>
<div>
<h4>Insert your text</h4>
</div>
</div>
</div>
Easier to accomplish with tables