File Under: HTML

Position Text and Images With Div Tags

Are you sick of putting align in every tag just to get a page to lay out properly? And how do you feel about table hacks for positioning images? I thought so. Well, never fear – the <div> tag is here.

Although it’s been around since HTML 3.0, <div> didn’t really catch on until CSS-based layouts became the rage du jour. It won’t solve all your problems, but it works for formatting large blocks of text, images, and just about anything else that has an HTML tag around it.


So let’s get started. Say you have some text, an image, and then some more text, and you want to center them on your page, like this:

Hi, I’m Mattmarg.’
monkey.gif
I reffed the big game between Bridgeville and Casterlin.

Now, you might be tempted to do something like this:

<h3 align="center">Hi, I'm Mattmarg.</h3>



<p align="center"><img src="monkey.gif"></p>



<h4 align="center">I reffed the big game between Bridgeville and

<a href="http:www.hits.org/casterlin/">Casterlin</a>.</h4>

But with a <div> tag, your code would look like this:

<div align="center">



<h3>Hi, I'm Mattmarg.</h3>



<p><img src="monkey.gif"></p>



<h4>I reffed the big game between Bridgeville and

<a href="http:www.hits.org/casterlin/">Casterlin</a>.</h4>



</div>

Cool, eh? The <div> tag will also work with other tags, like tables, forms, and lists.

Tips: What if you want those two paragraphs aligned to the left side of your page, but you want the image aligned in the center? Well, you can overwrite <div> tags by simply adding an align attribute to the tag you want to be different. Once the tag closes, the layout characteristics defined by the <div> tag take effect again.