How to center things - display:block/inline-block

user2335065 picture user2335065 · May 15, 2013 · Viewed 68.4k times · Source

When centering things in html and css, I find two approaches - either applying on the element :

display:block;
margin:0 auto;

or using:

display:inline-block;
text-align:center; (on the parent element)

I always wonder which is better and why. Thanks!!

Answer

gcoladarci picture gcoladarci · May 15, 2013

This is a classic and important question.

Elements can either be inline (meaning they all sit next to each other - like a span tag) or they can be block (meaning the stack up on top of each other - like a div tag).

Margin: auto, while a bit odd when you first see it, is the best and only way to center a block level (position static), element.

For anything that is display: inline (like a span tag) - the only way to center it is if you specify text-align: center on the parent. This will center everything display: inline inside it that is position: static;

Display: inline-block is a hybrid of the two that is relatively new (but supported as far back as ie7 if you use the hack mentioned in another answer). With inline-block, you get the benefits of inline, in that you can you stick a bunch of things next to each other and have them all be centered (think of a nav where all nav items are all centered), but ALSO have each item take advantage of some of the stuff you get with display: block - the most important one being HEIGHT.

Imagine a scenario where each nav item has a background image that is 80px tall - you can't make an inline element have a height of 80 - so you'd have to make each element display: block - only then can you give it a height. So to make them all appear next to each other, you'd float them. The problem is if you float them, you can't have them all be centered on the page unless you give a fixed width to the nav and margin: auto THAT. This means the nav has a fixed width - might be okay, but there are times when the nav has to have dynamic elements, different widths for different languages, etc.

Enter display: inline-block.