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 HTML. Plus, you avoid using deprecated tags and attributes like
CENTER. This article is for beginning web developers and will help you learn how to use the
DIV tag and CSS to center text and images on your pages.
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
CENTERtag in the document, start there.
Place your cursor before the first
<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.
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
DIVtag itself, or in a class in the head of the document.
Some older browsers don't like to center tables using a
DIVtag, so be sure to test in various browsers if you're centering a table.
For a more technically correct method of centering block-level elements, see my article How to Center Anything with CSS.
I have tested this technique using HTML5 and XHTML 4.01 strict DTD and it works in Chrome 1+, Internet Explorer 5+, Firefox 1+, Opera 6+, and Safari 1+.
What You Need