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 is very useful when you want to highlight some small content within a big paragraph or any repeated content to be highlighted horizontally.
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 CanadaHere is the example of span element html height
<style> .countryName { padding: 10px; margin: 10px; background-color: #f00; color: #fff; } </style> <span class="countryName">India</span> <span class="countryName">USA</span> <span class="countryName">Canada</span>
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; text-decoration:none; }
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
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.
$("span").click(function(){ // action goes here! });
You may be interested to read following posts