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.
Time Required: 2 minutes
- Open the Web page you want to update in your favorite text HTML editor.
- Find the elements you want to center on the page. If you already have a <center> tag in the document, start there.
- Place your cursor before the first <p> or <img> tag you want to center.
<div style="text-align: center;">
- Move your cursor to the end of the text or other elements (including images, tables, and so on) that you want centered.
- Delete any <center> tags and align="center" attributes you have around the centered section.
- Save your page.
- Test it in your favorite browser.
- You can put your style in the div tag itself, or in a class in the head of the document.
- 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.
- 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.
- 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