The complete guide to centering a div

Centering a div isn't as obvious as you'd expect

The complete guide to centering a div

Every new developer inevitably finds that centering a div isn't as obvious as you'd expect. Centering what's inside a div is easy enough by giving the text-align property a value of center, but then things tend to get a bit sticky. When you get to centering a div vertically, you can end up in a world of CSS hurt.

The aim of this article is to show how, with a few CSS tricks, any div can be centered; horizontally, vertically or both. And within the page or a div.

Centering a div within a div with inline-block

The text-align property only works on inline elements. The inline-block value displays the inner div as an inline element as well as a block, so the text-align property in the outer div centers the inner div.

Centering a div within a div, horizontally and vertically

This uses the margin auto trick to center a div both horizontally and vertically. It works with all modern browsers.

centering a div within a div, inner div responsive

What about Flexbox?

There's a new CSS3 layout model named CSS Flexible Box or flexbox which may make centering easier. However, it currently lacks full browser support. IE version 10 has partial support and version 11 has full support. Chrome and Firefox have full support, while Safari and iOS Safari have support with browser vendor prefixes.

We'll cover Flexbox in a revised version of this article when browser support approaches the mainstream.