Last updated on December 31, 2011. Tags: centering webpage, CSS layout, tableless web page layout
This is particularly useful for those webpages designed in a way that all block elements (content, menu, header, etc) are restricted to certain width (called fixed-width layout). There are usually two kinds of fixed-width layout; one wherein the elements are restricted on the left side, and the other wherein the elements are centered.
If a website has a fixed width, one thing you will notice is that when the browser window expands, the background color or graphic may expand as large as the monitor allows, but the width occupied by the content and navigation columns stay the same. For websites that are aligned to the left, the background expands to the right.
In case of websites that are aligned to the center, such as this website Codegrad, the background expands on both sides. However, in this tutorial, we will use a simpler webpage so that we can focus on the codes responsible for centering the webpage. Note that it is possible to have a layout aligned to the right, but I never encountered such a website.
Click here to see a simpler sample webpage with centered layout.
In our sample webpage above, even though it is highly advisable to place CSS codes in an external file, I decided to place the CSS codes in the header so that you can view them using the View > Source or View > Page Source of your browser. The part of the code that is responsible to the centered layout is the CSS code designated for div id="wrapper". In particular, it is the following lines of codes:
... found in this part of the CSS:
#wrapper {
width: 700px;
margin: 0 auto;
padding: 0;
border: 0;
background: #dddddd;
}
If you scroll down the source code of our sample webpage, you will notice that the div id="wrapper" is the outermost block element that contains all the other block elements in the layout. While you can have margins other than 0 (1px, 3px, etc), it is the inclusion of "auto" that ultimately enables the div id="wrapper" to center itself.
Hence, if you want to center a fixed-width webpage, set the margin of the outermost block element to "margin: n auto;" where n is the measurement of the margin that you want.
However, the "margin: n auto;" alone is not enough to center the webpage. The outermost block element must have fixed width assigned to it (in our example, it is 700 pixels). If there is no line of code assigned the width of the division, the typical behavior of the division is to expand according to the quantity of its content. Even if the quantity of the content is too small to fill the entire page, the division will still not align to the center.
Hence, both auto margin and fixed width are necessary to center the layout.
Important notes:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Posted by Greten on November 7, 2008 under Cascading Stylesheet
Comment Rules and Reminders