Close
The complete guide to centering a div

The complete guide to centering a div

2nd February, 2014
Labels:
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 in a page, basic

This method works with just about every browser, ever.
CSS
Example »
The value auto in the margin property sets the left and right margins to the available space within the page. The thing to remember is your centered div must have a width property.

centering a div within a div, old-school

This works with almost every browser.
CSS
HTML
Example »
The margin auto trick strikes again. The inner div must have a width property.

Centering a div within a div with inline-block

With this method the inner div doesn't require a set width. It works with all reasonably modern browsers, including IE 8.
CSS
HTML
Example »
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.
CSS
HTML
Example »
The inner div must have a width and height property. This doesn't work if the outer div has a fixed height.

Centering a div at the bottom of a page

This uses margin auto and an absolute-positioned outer div. It works with all modern browsers.
CSS
HTML
Example »
The inner div must have a width property. The gap from the very bottom of the page is set in the outer div's bottom property.

Centering a div in a page, horizontally and vertically

This uses margin auto again and an absolute-positioned outer div. It works with all modern browsers.
CSS
Example »
The div must have a width and height property.

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 browser support, mainly in IE (version 10 has partial support and full support won't arrive until version 11). Chrome, Safari and Firefox have support but with browser vendor prefixes.
We'll include Flexbox examples in a revised version of this article when browser support approaches the mainstream.
© 2014, Tipue. Made in London. post@tipue.com TOS