0
0
HtmlHow-ToBeginner · 3 min read

How to Create a Span in HTML: Simple Guide

To create a span in HTML, use the <span> tag to wrap inline text or elements. It does not change the layout but allows you to style or target specific parts of text within a block.
📐

Syntax

The <span> tag is an inline container used to group text or other inline elements. It requires an opening <span> and a closing </span> tag. You can add attributes like class or id to style or identify it.

  • <span>: Starts the inline container.
  • Content: Text or inline elements inside the span.
  • </span>: Ends the container.
html
<span>Some inline text</span>
Output
Some inline text
💻

Example

This example shows how to use <span> to color part of a sentence red using CSS.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Span Example</title>
  <style>
    .highlight {
      color: red;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <p>This is a <span class="highlight">highlighted</span> word in a sentence.</p>
</body>
</html>
Output
This is a highlighted word in a sentence. (The word 'highlighted' appears in bold red text)
⚠️

Common Pitfalls

People often misuse <span> by trying to use it as a block container, which it is not. It only works inline and does not create line breaks. For block-level grouping, use <div> instead.

Also, forgetting to close the <span> tag can cause unexpected rendering issues.

html
<!-- Wrong: Using span as block container -->
<span>
  <p>This is a paragraph inside a span (incorrect).</p>
</span>

<!-- Right: Use div for block elements -->
<div>
  <p>This is a paragraph inside a div (correct).</p>
</div>
📊

Quick Reference

  • <span> is inline and does not affect layout.
  • Use it to style or target small parts of text.
  • Always close the tag with </span>.
  • Use class or id attributes to apply CSS or JavaScript.
  • For block-level grouping, use <div> instead.