HTML <span> Tag

The HTML <span> tag is a generic inline container for inline elements and content. It is used to group elements for styling purposes, a better way to use it when no other semantic element is available.

Syntax:

<span class="">Some Text</span> 

Note: HTML <span> tag supports the Global attribute and Event Attributes.

Example 1: In this example, by using <span> tag, we can reduce code and HTML Attributes, see the below example that will display the same output as the above example with using <span> tag by applying CSS in a span tag.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        w3wiki span tag
    </title>

    <!-- style for span tag  -->
    <style>
        span {
            color: green;
            text-decoration: underline;
            font-style: italic;
            font-weight: bold;
            font-size: 26px;
        }
    </style>
</head>

<body>
    <span>
        w3wiki
    </span><br />
    <span>
        w3wiki
    </span><br />
    <span>
        w3wiki
    </span><br />
</body>

</html>

Output:

Span tag with CSS style

Example 2: In an inline tag, takes space as much as required and leaves space for other elements. All four-span elements will display in the same line because each tag takes only the necessary space and the rest of the space is free for other elements.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>w3wiki span tag</title>
</head>

<body>
  
    <!-- span tags with inline style/css  -->
    <span style="background-color:powderblue;">
        GfG
    </span>
    <span style="background-color: lightgray;">
        -Contribute-
    </span>
    <span style="background-color: yellow;">
        Article
    </span>
    <span style="background-color: lightgreen;">
        GCET
    </span>
</body>

</html>

Output:

Output

Example 3: Add a span tag inside a paragraph with id=”demo” We can change its text by applying javascript in this example GFG will be changed “w3wiki” after clicking on Button. 

HTML
<!DOCTYPE html>
<html>
<title>The span tag</title>

<body>
    <p>
        <span id="demo" 
              style="background-color:lightgreen;">
          GfG
        </span>
        A computer Science portal for Beginner
    </p>
    
      <!-- Creating button in java script -->
    <button type="button" 
            onclick="document.getElementById('demo').innerHTML =
                 'w3wiki!!!'">
      Change Text!
    </button>
</body>

</html>

Output:

Manipulate JavaScript with span tag

Browser Support

  • Google Chrome: 1
  • Edge: 12
  • Firefox: 1
  • Opera: 15
  • Safari: 1


Contact Us