Which to Use – div or span?

When I’m writing code for web pages, I normally have to stop to think when to use a <div> tag, and when to use a <span> tag. The big difference is that <div> is a block-level element while <span> is an inline element.

Block-level elements usually contain other elements, including text, inline elements, and other block-level elements. You can think of them as boxes. They are normally displayed with space before and after this box, unless you modify this behavior with CSS.

Inline elements usually contain text or other inline elements, and are displayed where they occur. They are usually used to give your document more semantic meaning.

Here is a simple example:

<div id="message">
  <p>The current date is <span class="date">August 28, 2007</span>.
  Labor Day is just around the corner.</p>
</div>

Notice how the <div> tag surrounds a chunk of content that contains a <p> tag, which is another block-level element. The <span> tag simply surrounds text within the content.

With these tags in place, we have plenty of hooks for CSS to use to format this content. By having the date in the <span> tag, we can do special formatting on the date if we choose.

Advertisements

2 comments so far

  1. Floyd Davenport on

    Brian,

    These examples are very helpful. I’m learning, but I need an example of how the div tag would be used for either formatting or some other purpose. 🙂

  2. […] some formatting on a <div> element. I built a test web page using the code from “Which to Use – div or span?” and some text borrowed from a recent ISU Extension News Release. Without any formatting, the […]


Comments are closed.

%d bloggers like this: