Ian McNally

Vertical alignment

May 19, 2014

Vertical alignment in CSS is as obtuse as its reputation suggests. I’m a huge fan of Flexbox, and I’m excited that it’s in the latest round of browsers’ support. In the mean time, I came across a great technique which involves a ghost element. Here are the essentials:

.parent {
    text-align: center;
}

.parent:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    margin-right: -0.25em; /* Spacing magic */
}

.centered {
    display: inline-block;
    vertical-align: middle;
}

It works great, and avoids the funky behavior that a table-styled element would have.


Ian McNally

Hey, I'm Ian. I build websites and write about what I learn as I go. Follow me on Twitter.