Adam Fraser
Adam Fraser

Reputation: 6635

centering fixed width elements with css

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;
}

Upvotes: 3

Views: 1085

Answers (3)

Zul
Zul

Reputation: 3608

http://reference.sitepoint.com/css/text-align:

text-align specifies how the inline content of a block is aligned, when the sum of the widths of the inline boxes is less than the width of the line box.

http://reference.sitepoint.com/css/margins :

Margin properties allow the author to control a box’s margin

Upvotes: 2

Alex
Alex

Reputation: 565

The text-align CSS property is only to be used when you have text to move on your page.

If you want to center a div in your screen you should always use margin: auto. Semantically speaking and in practice, margin: auto is the one that everybody uses when it comes to center blocks.

So, if you want to place h1, use text-align (see the link below, they use text-align on a header block).

Edit: See this page for common practice: http://www.w3schools.com/cssref/pr_text_text-align.asp

Upvotes: 3

Michael
Michael

Reputation: 763

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 auto and the display is the default: 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, the margin: 0 auto solution works.

P.S. the display: inline-block solution also works for variable width elements

Edit: Here is a jsfiddle with your examples but edited to show variable width elements and multiple inline elements.

Upvotes: 1

Related Questions