5

Possible Duplicate:
How do you easily horizontally center a <div> using CSS?

I have read multiple ways for centering content on a page using CSS. I am not talking about text, I am talking about content like images or a container etc.

What is the best way for centering content?

Setting the width of the box then using something like left: 50%?

I have read many many ways and really it gets confusing trying to understand which method truly works the best and is cross-browser friendly and works in older browsers.

Any ideas on what is truly the best and most effective way?

Thanks!

Community
  • 1
  • 1
L84
  • 45,514
  • 58
  • 177
  • 257
  • This has been asked like a million times. For example, http://stackoverflow.com/questions/618097/how-do-you-easily-horizontally-center-a-div-using-css http://stackoverflow.com/questions/114543/how-to-center-div-in-div – user123444555621 Jul 23 '11 at 05:03
  • I realize this has been asking a million times over but that is why I asked for clarification on which is truly the best method to use. Because when you read many of these you get a variety of answers. Thanks for the input => – L84 Jul 23 '11 at 05:05
  • As far as I read, the answer is always the same: use `margin-left/right:auto`. I'm not aware of any alternatives, but I'd be curious to learn some :) – user123444555621 Jul 23 '11 at 05:53

1 Answers1

4

Centering a div:

<div class="pageContainer">
    The awesome content is here
    <div> the secret of life....</div>
    .... more content ....
</div>

The Css:

body {
  width: 100%;
}
.pageContainer {
   width: 600px;
   margin: 0px auto;
}

this will horizontally center the div of width 600px on the page.

the margin: 0 auto; sets the left and right margin to whatever pixel left on the left and right of the page.

forexample if the width of the page is 800px, the margin left will be 100px and the right also 100px, moving the 600px at the center of the page

Ibu
  • 42,752
  • 13
  • 76
  • 103
  • for this simple use case i agree. but for more complex things i am also a fan of centered text-align on the body. for example if you want to bring in floating elements, absolute positioning... – The Surrican Jul 23 '11 at 04:24
  • I have read how margin: 0px auto does not work in older browsers. How true is this? – L84 Jul 23 '11 at 04:25
  • this works on safari, firefox, chrome, and IE7+. not tested on lower versions of ie – Ibu Jul 23 '11 at 04:27
  • If it works on IE7+ then I am good with it. My site does not play nice with IE6 or below so all is good. Thanks for the help and information. – L84 Jul 23 '11 at 04:30