How To: Achieve Vertical Alignment with CSS

The Problem

Have you ever tried vertically centering some content within an element such as a <div> or <span>? Using vertical-align:middle doesn’t work as you would expect it should. By default, these types of elements don’t respect vertical alignment (among other height-related settings). To get around this, many web developers resort to using <tables>.

Observe the following example:

//CSS
.BlueSquare{
    width:450px; height:200px; background-color:Blue;
    text-align:center;
    vertical-align:middle;
}
.RedSquare{ width:100px; height:100px; background-color:Red; }
//HTML
<div class="BlueSquare">
    <div class="RedSquare"></div>
</div>

Example_VerticalAlign1

Let’s take a look at how to get the Red Box to respect the vertical alignment.

Continue reading