Centering child HTML elements in containing element is very common in web development. This post presents several methods to achieve it and discusses their pros and cons.

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

Recipe 1: inline-block + text-align

The trick is that an inline-block element is just inline-like except that it can has width and height, thus it is affected by its parent’s text-align attribute.

This recipe works well in all the mainstream browsers, and just needs a little bit modification to work in IE 6/7: adding zoom: 1 in parent element’s css. However, it’s required to additionally justify child’s text-align property since it inherits center value from the parent.

Recipe 2: table + margin

Just set child’s display attribute as table, and use margin attribute to center in parent.

For detailed explanation about display: table and its variants, please visit this post: css layout based on display: table

In this recipe, we only need to set the css property in child element without change any css of parent. Recipe 2 supports IE 8+, and if you want to apply this trick in IE 6/7, you will need to change div with table and it’s not a good practice since table element has semantic information.

Recipe 3: relative position + transform

We can exploit the combination of relative parent and absolute child. With absolute child, we can move it with left property, and set it as half width of the parent. To remove the offset by the child’s width, just move child left half the width of itself and the transform property can achieve that.

The child won’t affect any element in the parent since it’s absolute positioned, and remove from the document stream. Since transform attribute are not supported by all browsers, you need to add some private prefixes sometimes.

Recipe 4: flex + justify-content

flex is powerful and we can just make the parent display as flex and set its justify-content property as center.

In this recipe we don’t need to care about the child and set the parent is enough. However, since flex is relatively newer css property, it’s not supported well in all the browsers and doesn’t work in old IE browsers.

By the way, you can also use child’s margin property without setting parent’s justify-content:

Conclusion

This post gives four feasible recipes for center child elements horizonally in parent. You should take careful consideration (e.g browser compatibility, etc.) before choosing one.