HTML a Day: <div> and <span>

There are 2 types of tags in this world: div tags and span tags. Mastering both is one of the foundational principles of HTML, as every tag in HTML is either classified as one or the other.

The div Tag

Div tags are dividers that separate a page into blocks. This means that if you don’t tell the <div> how wide it needs to be, it will stretch horizontally and take up as much space as possible. Keeping in line with a graphic design grid, imagine your website in a series of blocks. Paired with CSS, you can separate your whole layout into <div>s.

  1. Example 1: Basic <div> usage.
  2. Example 2: Laying out a website with <div>

Wherever you need a “block” of something, use a <div>tag. That’s why they are referred to as a block-level element. Although they have different default styles attached to them, these tags will behave similarly to <div> tags, filling up all horizontal space possible:

  • <p> — Paragraph
  • <h1>, <h2>, <h3>, etc. — Heading Tags
  • <ul> — Undordered (Bulleted) List
  • <ol>Ordered (Numbered) List
  • <pre>Preformatted Text (Preserve white spaces and line breaks; useful for displaying code)
  • <section> & <article>Same as div (differences explained here)

The span Tag

Span tags are inline elements. This means that unline div tags, they take up as little space as possible. Instead, they stretch over text, and are most commonly used to format a few words in a paragraph, insert a link, or even be used creatively for advanced text stylization.

  1. Example 1: basic <span> examples
  2. Example 2: <span> and CSS

Because span tags stay inline with the text, they are known as inline-level elements. These tags normally can’t fill up space, and are only used for styling within div tags. Some examples of inline tags include:

  • <strong>Bold (preferred alternative to <b>)
  • <em>Italic (preferred alternative to <em>)
  • <a>Anchor Link
  • <code>Code snippet (similar to <pre>, but doesn’t fill up space)
  • <small> — Small text
  • <sub>Subscript
  • <sup>Superscript

Exceptions

Remember how I said there were only 2 types of tags? Well, I lied. Technically, <table>, <img>, and <form> are neither block nor inline elements. As you might imagine, these are somewhere in between block and inline, but you’ll be able to figure these out in no time after you have a firm understanding of div and span.

TL;DR

Use div and p tags for big blocks of content.

Use span tags for text colors and styling.

Tips

  • Whenever you learn a new tag, find out whether it’s a block (div), inline (span), or neither.
  • You can change the tag’s display type between block, inline, or one of the other types using CSS’s display property.
Drew Powers is a frontend developer at Envy.