Using Auto Margins to Center DIVs with CSS - Building a basic fixed layout with CSS auto margins
(Page 2 of 4 )
The first method that I’m going to discuss regarding the construction of centered web page designs using CSS margins bases its entire functionality on auto margins. Despite its seemingly complex name, this approach is pretty simple to implement; it consists of assigning a value of “auto” to the left and right margins of a selected div to place it at the center of a web document.
Now that you have a vague idea of how to use auto margins, it’s time to demonstrate how to utilize them for creating a fully-centered web page layout. To do that, I’m going to code a few simple CSS styles, which will be attached to a sample (X)HTML file, similar to the example developed in the preceding article.
That being explained, here are the CSS code that implements the aforementioned auto-margins approach:
body{
padding: 0;
margin: 0;
background: #999;
}
h2{
margin: 0;
font: bold 18px Arial, Helvetica, sans-serif;
color: #000;
}
p{
font: normal 12px Arial, Helvetica, sans-serif;
color: #000;
}
#header,#footer{
padding: 10px;
background: #ffc;
}
#wrapper{
width: 800px;
margin-left: auto;
margin-right: auto;
}
#navbar{
padding: 10px;
background: #fff;
}
#navbar ul{
list-style: none;
padding: 0;
margin: 0;
}
#navbar li{
display: inline;
padding: 0;
margin: 0;
}
#navbar a:link,#navbar a:visited{
margin-left: 20px;
font: normal 12px Arial, Helvetica, sans-serif;
color: #000;
text-align: center;
text-decoration: none;
}
#navbar a:hover{
background: #fc0;
}
#maincol{
clear: both;
padding: 10px;
background: #fff;
}
In this particular case, I defined a group of basic CSS selectors, which will be responsible for styling a web document composed of the classic header and footer sections, then a navigation bar, and finally a main area. However, you should pay attention to the way that the DIV identified as “wrapper” has been styled, since this one is responsible for centering the whole web document.
As you can see, this specific DIV has a fixed width of 800 px, while its respective left and right margins have been assigned a value of “auto,” meaning that it will be positioned at the center of the web document. That’s all. Do you realize how easy it is to construct a centered layout using auto margins? I guess you do!
The previous CSS styles look rather disarticulated, however, when analyzed separately. Thus, in the section to come I’ll be coding the corresponding structural markup, to help you understand how these two layers can be linked with each other.
To learn how this integration task will be performed, go ahead and read the following segment.
Next: Adding CSS styles to a sample web document with some structural markup >>
More Style Sheets Articles
More By Alejandro Gervasio