Reputation: 2937
I'm about to write some templates for a new little Project - and I just wondered about one thing:
If I want my whole page content to be inside a centered column, with - lets say - 800px width, the usual way of doing that would be this (at least, this is the way I always did it):
<html>
<head>
<style>
body {
text-align: center; /* IE6 */
}
#wrapper {
margin: 0px auto;
width: 800px;
background-color: #eee; /* to see it better */
text-align: left; /* IE6 */
}
</style>
</head>
<body>
<div id="wrapper">
... content ...
</div>
</body>
</html>
Now, there is another method to do exactly the same thing, but with margin: -50%;
(or a fixed value, in this case margin: 400px;
), like this:
<html>
<head>
<style>
body {
margin-left: 50%;
}
#wrapper {
margin-left: -400px;
width: 800px;
background-color: #eee; /* to see it better */
}
</style>
</head>
<body>
<div id="wrapper">
... content ...
</div>
</body>
</html>
My question is - does one of this two methods have any advantages over the other? Or disadvantages? Is there a common 'best solution' for centering a main column?
Upvotes: 3
Views: 9556
Reputation: 3830
Since you are giving margin to the body of 50% to push the elements and again giving a negative margin to the wrapper to pull it in the previous place, this method works. But sometime browser doesn't render it properly.see the question here.
Upvotes: 2
Reputation: 4613
I only use the first method in this situation.
It's much more flexible because if I want to change the size of main div, or if I want to support other devices, there's a lot less changing needed.
The second method is a hack, and it's a hack that's not needed in modern browsers.
Upvotes: 2
Reputation: 5998
margin:0 auto;
will make sure there are equal amounts of space on either side of the element.
margin-left:50%;
is relative to the parent. For example, if the container is 1000px wide, you will have a left margin of 500px on the child element. However, that will not center the element, it will place it's left side in the middle — unless you hack it with a fixed value on the child element as in your example.
Usually, when you are dealing with a wrapper as in your case, margin:0 auto;
is the simplest and most flexible solution. In other cases, you might find it better to use a percentage or fixed value (for example, when floating stuff).
Upvotes: 7