Web Development optimize

How do I... Center a Web page layout using CSS?

The most common LCD monitors on the market today follow the wide-screen format. But that wide ratio can play havoc with Web site designers and their layout of Web pages. However, with a little bit of Cascading Style Sheet (CSS) code, you can control you Web page design by centering it on any screen despite its height to width ratio. John Lee shows you how to code it.

The most common LCD monitors on the market today follow the wide-screen format. That wide ratio can play havoc with Web site designers and their layout of Web pages. However, with a little bit of Cascading Style Sheet (CSS) code, you can control your Web page design by centering it on any screen despite its horizontal to vertical ratio.

This blog post is also available in PDF format as a TechRepublic download, which includes the sample code.

The situation

The next time you step into the local Best Buy store, take a look at their selection of computer monitors. You'll notice that as the screen ratio of monitors has shifted towards a more movie-theater like scale (rectangular) and away from a television ratio of 4:3 (square), the bigger a monitor gets, the wider it gets.

That's great for watching movies, playing games or running palette-heavy programs such as Photoshop, but what about surfing the Web? Long lines of text are hard and tiring on the eye, which is why you see so many Web sites that center their layouts. This allows the authors to set a fixed width for their content and present it in a dynamic fashion as the user's browser window expands and contracts in width.

You could, of course, create a fixed-width table and center it on the page, but today's Web designers and developers are trying to move away from tables altogether and instead control layout entirely with CSS markup. The small bit of CSS code that I am about to show you will get you started with using CSS to create your Web page layouts.

Open your preferred HTML editor and create a new page. Enter the code below (Listing A) to get started.

Listing A

<html>

<head>

<title>Centering a page layout with CSS</title>

</head>

<body>

</body>

</html>
Let's go ahead and place some formatted text in the Body of the HTML document (Listing B), so we can see the effects of our CSS code as we build it.

Listing B

<html>

<head>

<title>Centering a page layout with CSS</title>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>

Save the HTML document, and then preview it in your browser. Play with the width of the browser window to see how the copy expands and shrinks to match the size of the viewing area.

Let's start building the CSS code and tame all of that copy. Let's keep this simple and create your CSS code in the head of this document (Listing C) instead of linking to an external style sheet. Place it right immediately after the closing </TITLE> tag.

Listing C

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!--

-->

</style>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>
Most Web Designers, when declaring a CSS class that is going to be used as a centering element, give the class the name "wrapper" or "container." I prefer "wrapper," so that's what we'll use here (Listing D).

Listing D

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!-

#wrapper

-->

</style>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>
Next, we'll set the width of the wrapper to 720 pixels (Listing E), so that it will sit nicely on an 800 x 600 monitor. Of course, you could make the width as long or as short as you like to accommodate your design.

Listing E

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!-

#wrapper {

width: 720px;

-->

</style>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>
That sets the width of our content, but how do we center it? Simple -- the margin attribute shown in Listing F, with a setting of zero (0) and automatic alignment, places all of our content in the center of the screen:

Listing F

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!-

#wrapper {

width: 720px;

margin: 0 auto;

}

-->

</style>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>

Believe it or not, that small amount of code does the job... in most modern browsers. Older versions of IE and Netscape, however, have issues when complying with this CSS markup, and will center-align the text, when what we really want is the text to be left-aligned, but stay put in the center of the window. Don't worry though; there is a simple fix for these outdated browsers.

Start by defining a text-align attribute for the <BODY> tag of the HTML document, as shown in Listing G. You must place it before the wrapper style, or this will not work, due to the Cascading nature of Cascading Style Sheets!

Listing G

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!--

body {

text-align: center;

}

#wrapper {

width: 720px;

margin: 0 auto;

}

-->

</style>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>
Then add the text-align attribute below to the wrapper class and give it a value of left as in Listing H.

Listing H

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!-

body {

text-align: center;

}

#wrapper {

width: 720px;

margin: 0 auto;

text-align: left;

}

-->

</style>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>
There is one more line of code that needs to be written before we can test our work. Our wrapper will break in Netscape 6 if the browser window is shorter than the width of the wrapper. A min-width attribute (Listing I) in the body style will take care of that.

Listing I

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!-

body {

text-align: center;

min-width: 760px;

}

#wrapper {

width: 720px;

margin: 0 auto;

text-align: left;

}

-->

</style>

</head>

<body>

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</body>

</html>
Finally, apply the wrapper to the content of the HTML document by placing a <DIV> tag around all of the Gettysburg Address copy as shown in Listing J.

Listing J

<html>

<head>

<title>Centering a page layout with CSS</title>

<style type="text/css">

<!--

body {

text-align: center;

min-width: 760px;

}

#wrapper {

width: 720px;

margin: 0 auto;

text-align: left;

}

-->

</style>

</head>

<body>

<div id="wrapper">

<h1>The Gettysburg Address</h1>

<h2>Gettysburg, Pennsylvania<br>

November 19, 1863</h2>

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.

</div>

</body>

</html>

Preview the page in several browsers to see how the left-justified text stays put in the center of the browser no matter how small or narrow the browser window is.

Although we used no tables in this example, you could place whatever content you wish within the <DIV> tag -- tables included -- and the CSS structure would keep your layout in place in the center.

John Lee is a consultant specializing in design and illustration and a freelance technical writer. You can visit his Web site at johnleestudio.com.

92 comments
NewbieFORTRAN
NewbieFORTRAN

I am new to designing. Is a wrapper and a container the same thing? Good example above, I wasn't placing body align center and only using a wrapper or container and seems to work now. However, as with heathersh post on 18th Apr is necessary to use both divs and fixed sizes for all the different versions of window browser and for future tense purposes, I was going to start designing this way, but not sure if necessary.

heathersh
heathersh

First, thanks for the article, I found the straight-forward examples helpful. In response to the many posts on fixed sizing vs. percentages, I never use just one or the other and it's all based on how you want the pages to display. I generally create two wrapper divs. One has a percentage and the other fixed size. Based upon whether the images and other elements in the page can move around (if they can't I used fix) I apply the appropriate wrapper div. I did it on this site, for example, and all displays as you would hope. http://www.cheyennetechnology.com Thanks again, Heather

hiwaar
hiwaar

Hi all I would really appreciate your help in making our gate html page at http://www.hiwaar.com/ be at the centre We have no programming knowledge, so we appreciate your practical help. We are a charity non profit making human rights defenders organisation Any ideas or improvements regarding the design of the page would be highly appreciated Thank you

Hazlet
Hazlet

This is exactly what I need to do, and it works until I start playing with the CSS: So how do I do this working with Multiple Div layers. The page Im working on has 6 div layers and I cant seem to change the CSS in them with out it move off centre...get me?

katstuff
katstuff

OMG!!! Thank you, thank you, thank you! I have been tearing my hair out trying to convert all my table based layouts to css /div layouts, and I was just NOT able to figure out how to get a container wrapper and center, which is the place where I start with every page I do. Not sure if I will have more problems, but I was stuck at the very start. lol Kat

jdaniel59868
jdaniel59868

How well does this work in templates? Any recommendations since I have already built my site and then decided to center it? I used a template so I am hoping there is an easy fix.

si
si

When did the CSS terminology change so that a named instance (id attribute) was now called a class? What happened to the class attribute? Surely if you actually define a class then your CSS would look more like div.centered { ... } and the HTML becomes < div class="centered" > Has no-one else already pointed this out? Edit: formatting

studio.johnlee
studio.johnlee

I'm glad that this topic is being discussed so thoroughly, but I feel as if I should say that there are numerous ways to achieve almost any layout effect for a web page, be it CSS, HTML, XHTML, etc. As far as I am concerned, if your target audience/browser can display the desired results in a timely fashion, the technique works, period. Just because I write about a technique or method for coding web design does not necessarily mean that I am suggesting that you stop doing anything in the method that works best for you. I am simply offering instruction on one specific option that you may find useful. Context matters for everything, after all.

kathycookkc
kathycookkc

I'm new at web design: should I walk past the html books and go straight for xhtml? Or do I need both?

longwayoff
longwayoff

Commenting on relative versus absolute sizing: older browsers (like IE6) will refuse to enlarge text that's in absolute sizes, which is very annoying to us old geezers that can't read 8-point type anymore. I really hate going to View/Text size/Largest in IE6 and have NOTHING happen because the webmaster for that page was more concerned about his/her pretty layout than about anyone over 40 being able to actually read the page! One of the things I like most about Firefox is ctrl++ to make print bigger REGARDLESS of the code-specified size. Most newer browsers have an equivalent to the Firefox size changer these days (even IE7), but 36% of my users (public library in rural area) still use older versions of IE or Netscape.

SamirBeMad
SamirBeMad

Errrr, got something really stupid here...Was at a comic site the other day and I noticed the page was centered, was white space on either side so I checked out the source and I found that the designer had used tag right after the tag... Now I'm pretty sure it is not proper HTML and definitely not CSS, but it seemed mighty convenient, or does everybody already know this and I'm making a fool of myself? edit: spelling mistake...

brian.didlake
brian.didlake

Thanks for the refresher, I forgot how simple it is to format a webpage.

mdimis
mdimis

Rather than using a separate div tag, why not include all the styling in the body tag? Am I missing something?

brianchamps
brianchamps

Er... am I missing something here? I just: 'Select All' and click on the centre logo in Front Page. And the page is centred. OK, OK, sorry. So nobody uses Front Page any more. I'll get my coat.

leonttibsian
leonttibsian

I think I am going to do it your way. It just seems more correct... somehow. Sorry for the late reply.

dgs010243
dgs010243

Hi, Perhaps you will spend a little time browsing this page: http://dan.somnea.free.fr./2C/html_xhtml.css.php It belongs to an Initiation website covering many topics. I have a lot of HTML CSS examples. They are more elaborated than the w3schools examples. I have to admit that they are inspired from this very good URI resource. You could visit the topics developed by TechRepublic. At the same time you could visit my website, because you can find out internetjournal tutorials inside it. Good luck, prof dr ing Dan Gheorghe Somnea, Bucharest, ROMANIA

Tony Hopkinson
Tony Hopkinson

Unfortuanately. It's not some massive heartache though. In the main XHTML simply enforces 'good' HTML. Splitting out of presentation into CSS, is something you should have for either.

jmelnik
jmelnik

...to go for the most current technology. I would imagine that eventually html will be completely deprecated so why not go straight to XHTML/CSS... do not pass go and do not collect $200. I didn't find xhtml all that complicated, but i've been around since the beginning... hand coding sites in html with notepad, lol. Talk about painful. Personally, the obsessive-compulsive in me prefers the well-formed nature of xhtml and the separation of structure (xhtml) and presentation (css). It's also easier when working with a designer as they can concentrate on the CSS without disturbing the actual content too much.

KarrasB
KarrasB

And good site designers make their font 12 or 14pt. The smaller font size is to get more data on the page...not necessarily a viewer-oriented concept.

Sereniti
Sereniti

1) Browsers still support it. Browsers still support it because: 1) It's very rare for a site owner to either re-code a site him/herself or hire a webmaster to do it every time the standard changes. The entire Internet would implode on itself if every new version of a browser was not backward compatible to older standards because a gazillion web sites would break every time one upgraded to the next browser. I do wish, however, that the browser-makers would stop creating and implementing proprietary markup code! It only adds to the bad habits already proliferating. That said, I've always believed that just because you CAN do something doesn't mean you SHOULD. You can pound a nail in the wall with the heel of your shoe or even a heavy wrench, but it's more advisable to use a hammer. :) And if you continue to code to old standards, it's only a matter of time before your page WILL break. Code to the latest standard and your pages will last longer. (edit: to break up paragraphs)

deity_chooch
deity_chooch

Yes, you can style the BODY tag instead of a DIV tag to accomplish this, but it really depends on the layout you are looking for. I have been told before that it is always a good idea to begin with an all-inclusive DIV tag, but I don't necessarily subscribe to that school of thought. I think that a lot of web design can be done using the very simplest of tags and, as someone else said, too many DIV tags is detrimental to a site. The main purpose of separating the structure (HTML) from the style (CSS) is to ease the updating of a site, and if there is an overabundance of DIV tags this process is hindered. It all comes down to the golden rule of moderation: not enough of something may not interest people, yet too much will annoy them.

Jaqui
Jaqui

html is dead, xhtml does not accept styling of markup. xhtml 1.1 is the latest standard for website design and it requires use of css for styling. use html, it tells people you don't meet the standards for the industry.

Underground_In_TN
Underground_In_TN

The body tag should always be the main "wrapper". Too many divs is almost as confusing to read and maintain as table layouts. Plus, I've one minor correction to make on the article. The author says modern web designers are trying to get completely away from tables. This is not exactly true. Web designers no longer use tables as page layout structures, but tables are still fine for their original intent--tabular data. Now, if I could just get our Dreamweaver-using web designer to change to this paradigm...

jozhall
jozhall

This way the wrapper div isn't needed at all. CSS would look like this: body { width: 720px; min-width: 760px; margin: 0 auto; text-align: left; } "text-align: center;" is not needed because the default position is declared in the margins!

bob
bob

The main issue with FP is that it generates non-standard code. This makes it difficult for a developer who doesn't use FP to work on the code and sometimes creates display problems. The non-standard code glut in all MS applications is bemoaned by many. On the other hand, MS has the goal to make WYSIWYG work well in FP but achieves it by sacrificing standards with no hope that they will be accepted by the community. Its good to be the king!

Realvdude
Realvdude

I use it only for basic layout, then I move to the html page and clean up all the extra junk that Frontpage adds. The problem is that Frontpage only sees the objects of a page and does not consider the page as a whole, so it micro manages tags and formatting.

crose
crose

Frontpage is very useful - makes coding things a whole lot easier with "what you see is what you get" kind of deal - however, it is unfortunate, but true, a lot of Web hosting services do not support Frontpage extensions - and unfortunate that most "code cowboys" prefer to shoot from the hip and recreate everything from scratch instead of utilizing tools that expedite the process. Just my two cents - wait up I'll get my coat too :)

Sereniti
Sereniti

When I clicked the link, I got: Erreur 404 - Document non trouv? Page pr?c?dente

deity_chooch
deity_chooch

It seems that there might be some confusion as to what XHTML actually is, and you've hit the nail on the head. It's not some super-new, cool and crazy way to change things up in the web arena, it's well-formed HTML. You use the same tags with the same attributes, but now we make sure that every beginning tag has an ending and that every attribute is encased in double-quotes. Learning XHTML is really just learning HTML the right way.

KarrasB
KarrasB

Why did xhtml and xml become the so-called standard...do you know? Millions of sites are done with good old html...seems like it works.

jmelnik
jmelnik

the subject says: "Style body tag instead of using div?" You can style the body tag using CSS (instead of including it directly with the tag) in the same way you style a DIV using CSS. You can also style a div directly in the HTML which would render it invalid. I could be wrong, but the question seems geared at which tag you style... not whether or not you use CSS/xhtml.

klewis
klewis

i would consider using xhtml instead.. but this is a good basic example of what can be done with css to simplify web design.

blissb
blissb

Right -- HTML is dead the same way COBOL is dead... meaning not at all until a) no new browser supports it and b) all the legacy code is rewritten.... I agree with you in principle that web developers need to stick to the current standards. But until such a time as all the non-developers using things like DreamWeaver, Frontpage, and who knows what else to update sites change the practice of using HTML, the reality is far from the principle.

M.W.H.
M.W.H.

I'm very new to CSS but it looks like if I want to implement the DIV solution, I have to add an additional DIV to the top and bottom of each of my 50 pages so this BODY tag idea sounds perfect. Since every page already has a body tag, I can just add these lines to my main style sheet and voila. Unfortunately these lines don't seem to work in IE7 (works flawlessly in FF3 and Chrome) body { width: 720px; min-width: 760px; margin: 0 auto; text-align: left; } Any idea what's missing?

crose
crose

I agree it isn't the cleanest way to go and I appreciate all the comments. I am an idealist and prefer the best of both worlds - A WYSIWYG program that develops pristine code- don't want much do I? I just feel that the Web is such a majorly visual entity - and I am a visual person too -

deity_chooch
deity_chooch

I don't have a problem with WYSIWYG programs, but out of all that are available I'd have to say that FrontPage is probably the worst (Note: I have not used many, just a few). FrontPage does its job: allows anyone to create a web page who can maneuver in Microsoft programs. But it does include a lot of bloat that people like me (code cowbodys?) do not appreciate. If I were to use a WYSIWYG editor, I'd go with Dreamweaver as it minimizes the wasted code, even though there is still some. I actually don't even like the small amount of bloat that Dreamweaver puts in, so I use a text editor called vim. It gives me absolute and complete control over what is going on in the page and I know that I'm going to be able to read the code of the page easily.

Tony Hopkinson
Tony Hopkinson

How many times have you had to wade through browser compliancy issues, even the ame browser but different versions. Browser specific extensions. Sites that say FF refuses to load, or makes a complete hash of, your beautiful design, looking like a steaming turd on some on else's set up. Then there's the cost in code of supporting all this legacy stuff. Just dealing 'sensibly' with the requirement to allow mixed up start and tags cost's a relative fortune in the code.

Jaqui
Jaqui

the newer standard is designed to make it easier. getting css to work with an html page is not always easy, where it is with xhtml.

deity_chooch
deity_chooch

Yes, you are reading it correctly. I'm not exactly sure of the "why" for the syntax, but I'm guessing that since XHTML is just well-formed HTML, the W3C didn't feel the need to change the DOCTYPE tag. Also, you may note that there is Transitional XHTML and Strict XHTML which have slightly altered DOCTYPE tags. I prefer to use the Strict XHTML, but it can be a pain to learn and Transitional is much more forgiving. Side note: I'd recommend the CSS Zen Garden to anyone who is interested in web development; it is an excellent example of what we are trying to accomplish by separating the structure from the style.

Sereniti
Sereniti

I'm not as savvy about the current standards as most of you here and have been learning a lot from this thread - thanks! If I'm reading this right, I believe Dreamweaver's default doc type has been XHTML doc type for the last two, maybe three versions. CS3's default doc type is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> I find that confusing, because it opens with "DOCTYPE html..." and then declares "...DTD XHMTL..." So, am I reading it right? If not, what should the declaration be? Although I can hand-code XHTML and CSS in my sleep using Notepad, I love using Dreamweaver because it streamlines my process. I can always go into code view and remove the bloat or re-tag something that isn't quite right. That's still faster for me than anything else. I'm working on keeping all my layout styling in CSS with no HTML. To check it, I use the Firefox web developer toolbar to view my pages with all styles disabled. When I see a single column of text aligned to the left with no images or tables, then I'm satisfied! LOL I've found CSSzengarden.com to be a great help, along with W3schools.com.

Underground_In_TN
Underground_In_TN

I could do that, but my Dreamweaver-loving web designer will just let Dreamweaver put in another DocType. And she won't listen to lower-caste programmers like me, especially about religious matters like web design tools.

Jaqui
Jaqui

if the people making the apps removed the html doctypes from the apps. not have them as the default. but, I'll keep saying it's dead, to try to drive that point across to those who aren't removing the doctypes from the apps and keeping them as the default.