4.3 Span | HTML

4.3 Span
Table of Contents

The <span> element in HTML is a generic inline container used to apply styling and other attributes to a specific section of text or inline content. Unlike block-level elements, which typically create a visible block on the page (like paragraphs or headings), the <span> element is used to apply styles or other attributes to a smaller inline portion of text within a larger block of content.

Basic Usage of <span>

The most common use of the <span> element is to apply CSS styles, classes, or inline styling to a specific portion of text without affecting other parts of the surrounding text. It is often used when more specific control over styling or scripting is needed within a paragraph or other inline content.

Example of Using <span> with CSS

<p>This is an example of <span style="color: blue;">styled text</span> within a paragraph.</p>

In this example, the text "styled text" will appear in blue due to the CSS style applied to the <span> element.

Example of Using <span> with Class

  .highlight {
    background-color: yellow;
    font-weight: bold;
<p>This is an example of <span class="highlight">highlighted text</span> within a paragraph.</p>

In this example, the text "highlighted text" will have a yellow background and bold font weight due to the CSS class applied to the <span> element.

Usage with JavaScript

The <span> element is also commonly used with JavaScript to dynamically manipulate or apply behavior to inline content. For example, JavaScript can be used to change the text or style of a specific <span> element based on user interaction or other events.

Example of Manipulating <span> with JavaScript

<p id="example">This is an example of <span id="dynamic">dynamic text</span> within a paragraph.</p>
  var spanElement = document.getElementById('dynamic');
  spanElement.textContent = 'changed text';
  spanElement.style.color = 'green';

In this JavaScript example, the text content and color of the <span> element with the id "dynamic" are dynamically changed.


The <span> element is a versatile inline container in HTML used for applying styling, classes, or other attributes to specific sections of text or inline content. It provides a way to target and modify small portions of content within larger blocks without affecting the overall structure of the document.

I am a passionate writer. Read more.

Post a Comment

Don't spam links or promote stuff in the comments. It's annoying and lowers the conversation quality. Contribute respectfully and helpfully instead.