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?
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).