The previous post introduces several ways for centering elements horizontally. In this post, several recipes will be given for centering child elements in parent element vertically.

The basic HTML page structure is as follow, where a child div is contained in a parent div:

Note: In the following examples, if the height or width property is set, it’s only for more intuitive demonstration, the recipes can be suitable for adjustable height and width.

Recipe 1: table-cell + vertical-align

Treat parent div as a table cell and set its vertical-align property as middle.

For some older browsers, we can use table and td tags instead, and this recipe have good browser compatibility.

Recipe 2: relative position + transform

Similar to horizontal centering, we can use the combination of relative position and the transform property to achieve vertical centering.

It’s simple and intutive except that we need to add some private prefixes to support different browsers.

Recipe 3: flex + align-items

Set the parent div display as flex and the default value for align-items is strench, which will makes the child div take all the height of the parent. Just set the align-items as center, and all is done.

It’s the simplest solution and we only need to set the parent’s properties, but currently flex layout is not supported well in all browsers, so consideration need to be taken before taking this one.

Conclusion

This post gives three recipes for centering child elements vertically, each one has its own pros and cons. Combining the tricks of horizontal and vertical centering, we can achieve the two at the same time. In the future, I’ll give some recipes to achieve that.