1. Computing

Discuss in my forum

How To Center Text or Images with the DIV Tag and CSS

By , About.com Guide

Centering elements using CSS and a <div> tag is easy. And once you've centered your text or images in this fashion, you'll know that it will be valid XHTML. Plus, you avoid using deprecated tags and attributes like align and center. This article for beginning Web developers who are new to HTML and CSS will help you learn how to use the DIV tag and CSS to center text or images on your pages.
Difficulty: Easy
Time Required: 2 minutes

Here's How:

  1. Open the Web page you want to update in your favorite text HTML editor.
  2. Find the elements you want to center on the page. If you already have a <center> tag in the document, start there.
  3. Place your cursor before the first <p> or <img> tag you want to center.
  4. Type
    <div style="text-align: center;">
  5. Move your cursor to the end of the text or other elements (including images, tables, and so on) that you want centered.
  6. Type
    </div>
  7. Delete any <center> tags and align="center" attributes you have around the centered section.
  8. Save your page.
  9. Test it in your favorite browser.

Tips:

  1. You can put your style in the div tag itself, or in a class in the head of the document.
  2. Some browsers don't like to center tables using a div tag, so be sure to test in various browsers if you're centering a table.
  3. Using this technique may cause problems in the future, as CSS 2 indicates that the text-align property is only for inline elements, not block - like images and paragraphs.
  4. I have tested this technique using even XHTML strict DTD and it works in IE 5+, Firefox 1+, and Safari 1+.

What You Need

  • Text Editor
Related Video
How to Align Text in a CSS document

©2013 About.com. All rights reserved.