Span element in html example

span tag is almost like a div tag in Html, but there is some differences
span tag occupy the space of the of content size, means if my content width is 100 pixel and I put that content inside a span tag, by default the span width will be 100 pixel same as content width, on the other hand div tag will occupy the entire width of screen by default.

Things to remember about Span tag use in Html!

  • Span tag is just like div tag, but doesn't occupy the horizontal space
  • Span object does not have any shape; it takes the space of content inside
  • Span element is good for highlighting in-line html text or element

When to use span tag in html page design

Span is very useful when you want to highlight some small content within a big paragraph or any repeated content to be highlighted horizontally.

Let’s look at some <span> example

Here we will write few country name, each country name will be written inside a span tag like this way, you can see how to change span tag background color in html.

India USA Canada

Here is the example of span element html height

        padding: 10px;
        margin: 10px;
        background-color: #f00;
        color: #fff;
<span class="countryName">India</span>
<span class="countryName">USA</span>
<span class="countryName">Canada</span>
Change span background color

You can change span background color on mouse hover, look at example below.

.spantagClass {
padding: 10px;
margin: 10px;
background-color: #f00;
color: #fff;
.spantagClass :hover {
    background-color: #0578ce;
    color: #fff;
.spantagClass :hover a {
    background-color: transparent;
    color: #fff;

span tag example in html

difference between span and div tag

Span tag never occupy the complete horizontal space like Div, when you specify small content like one work or two word inside a Div, it takes the whole horizontal space (blocks the entire width), but span takes only the length of that content, if you want to highlight small content like one or two word then span is more appropriate than div, you also can use span as button

look at the above exampel of span, if you write same thing in div then it may look like example below

<div class="countryName">India</div>

You may also read Div in HTML Example

Span element in javascript

When designing interactive webpage you may come across situation when you need to know how to get the text of a span element, or get value of span tag in JavaScript and change the value dynamically.

We can change the value of innerHTML of any span tag using JavaScript, we can access span tag either by id or by class name.

document.getElementById('spanId').innerHTML = "New Value";

You also can access span tag using jQuery and change the value or inner text. access span element by class name, id or by type like example below.

      // action goes here!

You may be interested to read following posts

HTML Tutorial | Web Designing Course | HTML5 Introduction