Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Basics (2014) The Box Model Margins

stephanie sutedja
stephanie sutedja
3,693 Points

text align: center; margin: auto; Which one is better?

Hello, I'm wondering for centering elements is it better to use: text align: center;

or

margin: auto;

Which one is better?

Thank you.

3 Answers

Hi Stephanie,

As already suggested it really depends on what you are trying to centralise, if you are looking to have your headers i.e h1, h2, h3 centred, or you "p" tags centred then use text align this is what is designed from without then having to worry about block inline-block or inline elements.

Margin auto would be used to centralise the parent element that holds the text content on the page and to do this you would have to specify a width for both the parent and child. For example:

<body>
    <div class="text-wrap">
        <div class="center">
            <h1>Center Heading</h1>
            <p>All my text in this section would be aligned left as default</p>
        </div>
    </div>
</body>
.text-wrap {
  width: 100%;
}

.center {
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}

h1 {
  text-align: center;
}

The above is how I would use both properties to achieve the end goal you would be looking for.

Hope this is helpful! Craig

It really depends on what you are trying to achieve.

If you are trying to center a element with a known width then you should be using margin: 0 auto;.

If you are trying to center the content of an element ( text, images etc.) then you should be using text-align: center.

Although it's possible to center block elements with text-align: center by settings it's display to inline ( or inline-block ) and using text-align: center on the container you probably shouldn't.

Robert Karlsson
Robert Karlsson
8,021 Points

It depends if the element is a block or an inline element. The block element you can center with margin: auto, and an image you can center with text-align: center.