Saturday, May 27, 2006

CSS, XHTML, and Centering your Web

Centering your web page can be an issue. I looked around the web to find a myriad of information about how to use auto margins and, frankly, hacks that will only work in one browser and maybe another. As an avid MySpace user, I used MySpace as a resource to find how to change my blog look and found a blog there that gave me invaluable insight on how to center a web page. It's really fairly simple; you will be as surprised as I was.
First, I'm going to show you the HTML/XHTML code. I'm not going to show ALL of the code, just what you need to mess with in order to get the page centered. You will start with the <body> tag and then follow with <div> tags. You will normally have more than one <div> element (this is important) that is "contained" by a single "container" <div> element; as follows:
<body>
<div class="container"> <!-- this is your container DIV -->
<!-- below are the rest of your DIV elements -->
<div>
<p>Content Here</p>
</div>
<div>
<p>More Content Here</p>
</div>
<div>
<p>Even MORE Content Here!!</p>
</div>
</div> <!--this final closing DIV closes the first DIV with a class of "container" -->
</body>
So, you have 3 different DIV elements within a single DIV "container". This is how we affect the alignment of ALL the contained DIVs. I do not recommend using table tags at all. Tables are being deprecated with exception only to tabular data. There's nothing you can't do with XHTML/CSS, so I encourage you to use it.
The following is the important code to use with CSS to make your page center. It may seem confusing at first, but it's really very, very simple! You must define a width of the page, say, width: 700px. Then, you need to bring the whole container back HALF the size of the width using the margin-left attribute; margin-left: -350px. Next, you will tell the screen to position itself 50% of whatever the resolution is (the beauty of this is, no matter what the resolution is of the viewer, your page will always be centered. You do this using the left: attribute and assigning it as such: left: 50%. Here's the CSS:
body {
margin: 0;
padding: 0px;
background: #000;
color: #fff;
border-style: none;
}
div.container {
margin: 0;
padding: 0;
width: 700px;
margin-left: -350px;
left: 50%;
position: absolute;
}
//*then the rest of your CSS code for your other DIVs may follow - Remember, you should assign a "class" to all DIVs you wish to affect separately, otherwise, simply putting div { whatever in }, will result in ALL unclassed DIVs taking on the SAME format, positioning, etc... *//



Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1¢/min.