The HTML <span> Element

What Is <span>?

The <span> tag is an inline container used to wrap a portion of text or inline elements for styling or scripting purposes. By default, it does not introduce line breaks or affect the surrounding layout.

It’s considered a generic inline element, meaning it carries no semantic meaning on its own—its purpose is purely structural and presentational. Developers often apply class or id attributes to a <span> so it can be targeted with CSS or manipulated via JavaScript.

When to use:

  • Highlighting part of a sentence with a different color or style.
  • Applying a tooltip, hover effect, or animation to specific words.
  • Wrapping inline icons or symbols alongside text.

When not to use: Avoid using <span> for structural layout; use semantic or block-level elements for larger sections or meaningful grouping.

Example of highlighting text:

<p>This is a <span class="highlight">highlighted</span> word.</p>

Use Cases

  • Change the color of a specific word or phrase
  • Target inline content with a class or ID
  • Add interactivity with JavaScript

Syntax

<p>This is a <span>highlighted</span> word.</p>

By default, the <span> doesn’t apply any visible effect until styled.

Adding Class or ID

To make <span> useful, assign a class or id to it:

<span class="red-text">Warning</span>

Inline Nature

Unlike <div>, the <span> element is inline—it does not break the flow of text.

<p>This <span>will not</span> start on a new line.</p>

Semantic Use

Use <span> when no more specific semantic tag applies. It should not be overused in place of meaningful elements like <strong>, <em>, or <mark>.

Practice Prompt

Use <span> to highlight a word in a sentence with a yellow background using CSS:

<p>This is a <span class="highlight">special</span> message.</p>

<style>
  .highlight {
    background-color: yellow;
  }
</style>

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic