J. Blustein

Web-centric Computing

Some Example Code

How To Centre With CSS

The text-align property in the CSS2 standard applies only to block level elements. So you can use it to centre text within a p or div element, for example, but you cannot use it to centre the p or div itself.

Some old WWW browsers (Internet Explorer version 5 for example) do centre block level elements when text-align:center applies. But later browsers implement the standard as it is written.

Eric Meyer* suggests centring block level elements this way:

  1. either
    1. set the element to have a fixed width
      • use pixels (px) for images, or
      • use exs or ems for fixed-size text
      or
    2. use %
  2. set the margin-left and margin-right properties to auto
  3. include text-align:center for old (non-compliant) browsers

Here is an example (from page 168 of a book by Eric Meyer*) used to centre an image:

   <style type="text/css" media="screen">
      body     {text-align: center;}  /* IE5.x workaround */
      div#card {width: 575px; margin-left: auto; margin-right: auto;}
   </style>

* Full citation to book
Eric Meyer on CSS: Mastering the Language of Web Design by Eric A. Meyer; Published in July 2002 by New Riders; Copyright ©2003 by New Riders Publishing; ISBN 0-73571-245-X.
Comments on the book
If you want to learn about the CSS standard and how it is meant to be implemented for all time then I recommend Cascading Style Sheets: Designing For The Web (2nd edition) by Lie and Bos. (The full citation is in the list of reference books.)
But if you want to know how CSS is being used now and see some excellent examples of how to use it to create beautiful, and mostly accessible, webpages then seek out recent books by Eric Meyer and his CSS website.
http://www.cs.dal.ca/~jamie/course/CS/4173/examples/CSS/buttons/centre.html
Version:
23 March 2003
CS 4173 Prof.:
J. Blustein <jamie@cs.dal.ca>

This document is written in valid XHTML 1.0 &
This document makes use of cascading style sheets.