Vertically centering elements with CSS

Vertically centering elements used to involve tables. But as we all know it is an antipattern to use tables for layouting purposes. The following will show how to solve this without tables by using CSS. As an example I will show how to vertically center an image in a div – but this will also work with other elements that have a fixed size (e.g. a login form).

Let’s have a look at the following HTML code snippet:

<div>
    <img src="...">
</div>

Simply setting vertical-align: middle; on either of the elements will not make the image to be vertically centered in the div.

To solve this, we need a helper element with height: 100%; in the div that causes the line height to be equal to the height of the div itself. Additionally this helper element must be styled with display: inline-block;. Now you can set vertical-align: middle; to both the helper element as well as the image itself.

The following code shows a complete example that works in all modern browsers (IE8+, Webkit, Firefox):

<style>
#parent {
    height: 200px;
    width: 200px;
}

.helper {
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

.centered {
    vertical-align: middle;
}
</style>
<div id="parent">
    <span class="helper"></span>
    <img class="centered" src="...">
</div>

As already said before, this trick will also work with elements other than images. To make this work with e.g. a div you have to ensure that the element is set to display: inline-block;.

Short URL for this post: https://wp.me/p4nxik-1QP
This entry was posted in Web as a Platform and tagged , , . Bookmark the permalink.

Leave a Reply