I’ve found two common ways of centering a fixed-width element horizontally with CSS, and I was hoping someone could help me more deeply understand when one might use one technique rather than the other.
One technique involves using text-align:center while the other involves margin:auto.
Below I’ve illustrated how both can be used to achieve the same thing. Looking at the code, it’s tempting to say that the margin:auto method is better all-around, but I can’t help but wonder if there are other better ways to do this sort of thing, or if there are cases for which the text-align method is preferable.
You can see the example code here: http://dabblet.com/gist/1634534 or below:
<div class="wrap1">
<h1>Hey now</h1>
</div>
<div class="wrap2">
<h1>Hey now</h1>
</div>
h1 {
background-color: #CCC;
width: 200px;
}
div.wrap1 {
text-align: center;
background-color: blue;
padding: 5px;
}
div.wrap1 h1 {
display: inline-block;
text-align: left;
}
div.wrap2 {
background-color: red;
padding: 5px;
}
div.wrap2 h1 {
margin: 0 auto;
}
I think the answer is in the implementations.
Wrap1 uses
display: inline-block. By making the element inline-block elements around it will be “inline” with it, meaning it will visually be displayed horizontally on the same plane.Wrap2 uses
margin: 0 autoand the display is thedefault: block. This of course makes the element a block element and therefore it will visually be displayed on it’s on line.The conclusion is if you want to center a bunch of inline objects, use
display: inline-block. If you are centering a single block element, themargin: 0 autosolution works.P.S. the
display: inline-blocksolution also works for variable width elementsEdit: Here is a jsfiddle with your examples but edited to show variable width elements and multiple inline elements.