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!!
Try using this: margin: 0 auto; Or text-align: center; on the parent <div> ...
To center an inline element like a link or a span or an img, all you need is text-align: center . For multiple inline elements, the process is similar. It's possible by using text-align: center .
To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
Block level elements We can center a block-level element by giving it margin-left and margin-right of auto (which has a known specified width):
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.
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.
You can also use display: flex
now:
.parent { display: flex; justify-content: center; } .block { width: 200px; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With