Archive

Posts Tagged ‘div’

HTML Tip: Should I use a div or a span?

March 17th, 2009

This comes up a lot in the web development world, especially with higher level coders who are in the Java or .NET world. After just having this coversation with a coworker, I came up with a metaphor to explain the relationship between block and inline elements. A few basics first.

A div is a generic block element with no inherent attributes. By default, it’s as wide as its parent element, and breaks the line. A few common block elements are DIV, P (P is special, we’ll get to that), and BLOCKQUOTE.

A span is a generic inline element with no inherent attributes. By default, it’s as wide as its content, and doesn’t break the line. Some inline elements you’d be used to seeing are the STRONG, EM, SPAN, and STRIKE tags.

To write valid XHTML, you need an understanding of what elements can be properly nested… which is pretty simple. Block elements can be nested in block elements, inline elements can be nested in block or inline elements. Easy peazy. Well, almost.

The exception to this is the P tag, which is a block element, but breaks the rules by only being allowed to contain inline elements. The nesting order DIV DIV P EM STRONG is fine, but DIV P DIV EM STRONG can’t validate because you’re nesting a block element inside the P tag.

Here’s an easy way to remember it. Imagine block elements as pieces of blank paper, and imagine inline elements as ink. You can stack as many pieces of paper as you want on top of each other, and you can contain anything written in pen on the paper. You can use the pen on a few pieces of paper and lay them out on a larger piece of paper, you can underline pen with pen, you can bold text by writing with more pen over the pen. You can’t put paper into the ink… that relationship only goes one way. 

Imagine the P tag is a lined piece of paper. All of the same ink rules apply, but if you try to put more paper into it, you won’t be able to see the lines usefully, so that’s a no-no.

So there you have it. To put it simpler, If you need a container, use a div. If you need to effect these three words, use a span.

Joisey Mike Design, The Internets , , ,