Ways to Vertically Center Child Elements in Parent
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
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.
div as a table cell and set its
vertical-align property as
For some older browsers, we can use
td tags instead, and this recipe have good browser compatibility.
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.
Set the parent
div display as
flex and the default value for
strench, which will makes the child
div take all the height of the parent. Just set the
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.
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.