user2335065
user2335065

Reputation: 2547

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

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!!

Upvotes: 60

Views: 204817

Answers (3)

evuez
evuez

Reputation: 3387

Block elements should always be centered using

.block {
    margin-left: auto;
    margin-right: auto;
    width: 600px;
}

as stated by the w3c: http://www.w3.org/Style/Examples/007/center.en.html#block

text-align: center;

is well-named: use it to center texts.

Update

You can also use display: flex now:

.parent {
    display: flex;
    justify-content: center;
}
.block {
    width: 200px;
}

Upvotes: 47

gcoladarci
gcoladarci

Reputation: 1119

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.

Upvotes: 35

Vinícius Moraes
Vinícius Moraes

Reputation: 3516

There is no better way in this situation both approach will work and both are corrected. Just one thing display:inline-block doesn't work on IE7 (if you support this browser) you will need a hack to make it work

display: inline-block;
*display: inline;
zoom: 1;

Upvotes: 5

Related Questions