Monday, October 4, 2010

Css tutorial : Centering with margin: auto

The best way to center an element with CSS is to use the auto value for left and right margins.
For modern browsers, all this requires is a set width rule (as without it the box would naturally
stretch to fit its container—in this case the browser window) and the left and right margins
given the auto value. Building upon the earlier example, we have the following rule:
/* Container for centering all our content */
#container {
width: 400px;
margin: 10px auto 10px auto;
padding: 20px;
border: 1px solid #000;
background: #CCC;
}
Most browsers are happy with this, although IE5/Win fails miserably, usually aligning the
element to the left. At the time of writing, most IE users are using IE6, and IE7 is on the way, but
the percentage of IE5 users is significant enough to warrant consideration.
There is a way of making it work for IE5/Win, and it’s quite simple. The trick is to make use
of the text-align property in the container’s parent element (in this case that is the <body>) to
center the container. The downside is that all child elements within <body> will now correctly
inherit that value and center all their content, which isn’t good. Therefore text-align: left is
applied to all main division elements to counter the centering:
/* Define default values for the whole site */
body {
text-align: center;
}
/* Container for centering all our content */
#container {
width: 400px;
margin: 10px auto 10px auto;
padding: 20px; border: 1px solid #000;
background: #CCC;
text-align: left;
}
This approach ensures that the container is centered horizontally in the browser window
whatever browser is used, and acts as the perfect basis for any centered design (see Figure 3-6).

No comments:

Post a Comment