Easy CSS Centering
|
Andrew Martin Creative Director |
The invention and evolution of CSS over the past decade has revolutionized web design. Making it a much more efficient and flexible medium. This is not absolute, however, as there are still a few things that are a lot easier to do with tables (no matter how many times you flame me, web standards Nazis, it is still true). One of them is centering your entire website on the page. My personal opinion is that, over the years, I have cut back my use of tables for layout to a reasonable level - I don't use them unless I have a good reason. That said, I found many of the ways used to center entire sites using pure CSS to be cumbersome, until I came across this particular one. Unfortunately, I can't remember where. Regardless, here is the simplest way I know of to use pure CSS to center your entire webpage.
- You must use absolute positioning on your <div> tags. (Learn about CSS positioning)
- You must calculate the width of your entire site, in pixels. Remember this number.
- Use the following code in your stylesheet (this code assumes a site width of 800px, so make sure to substitute with your own numbers):
#wrapper { position:absolute; left:0px; top:0px; width:800px; /* width of site here */ left: 50%; margin-left: -400px; /* divide site width by 2 */ } - Place the following code in your HTML files (notice that the <div> tag and its respective closing tag are the first and last tags in the <body> section of your HTML, hence the name 'wrapper'):
<div id="wrapper"> <!-- place directly after the <body> tag --> <!-- all the rest of your HTML goes here --> </div> <!-- place directly before the </body> tag -->
- If you are using a site with a fixed height, you can use the same tactic to vertically center the entire page, replacing the CSS code with the following (code assumes that the site is 800px wide and tall):
#wrapper { position:absolute; left:0px; top:0px; width:800px; /* width of site here */ left: 50%; margin-left: -400px; /* divide site width by 2 */ height:800px; /* height of site here */ top: 50%; margin-top: -400px; /* divide site height by 2 */ }
|
|
Design Blog
Industry News
Recent Design Blog Entries
- Web Design, Usability, and a bit of SEO - It's a Rap!
- HTML from Square One: Format Text
- HTML from Square One: Doc Setup
- Web 2.0 Tools for Modern Business
- Bloggers - Free and Low Cost Imagery
- Bloggers - How NOT to Use Type
- Bloggers - Resize The Right Way
- Does the 800 Wide Limit Still Apply?
- The Quality of Quality Content
- SEO - Importance of Keyword Research
- The Best $100 a Mac User Ever Spent
- 5 Solid, Free Script Fonts
- Easy CSS Centering
- How to 'Save for Web' in Photoshop