15

I am curious, the span tag seems to work the same as a div.

0

3 Answers 3

23

The main difference is that the <span> tag is an inline element, whereas the <div> tag is a block level element.

Two block level elements (divs) will be displayed one after each other vertically, whereas two inline elements (spans) will be displayed one after each other horizontally.

To understand the difference in visual terms, it might help to think of the <span> element as a word and the <div> element as a paragraph: divs are generally used for laying out blocks of content. Spans are normally used for highlighting groups of words within that content.

11

Both Nick and Toby have answered your question nicely, but to take it one level further.

By default, <div>s are block elements and <span>s are inline elements. These are generic tags that simple provide block or inline containers. In practice, these can be twisted via CSS to be somewhat interchangeable by setting the display css-attribute to 'block', 'inline' or even 'inline-block' (amongst others).

However, bending them to act like one another isn't recommended. And, there are rules in HTML that actually prevent using block-level elements inside of other elements (mostly inline elements like the <a> tag), so, you should try to use the right tag where it is appropriate and only try to override their behaviour when absolutely necessary.

Try to think of them as semantic elements. Use <span> when you want to tag content used inside of blocks of text, for example and use <div>'s when you need to add extra structure to the page itself.

Having said this, HTML5 has a plethora of semantic elements that should significantly reduce needing to use either of these generic tags. Using semantic tags is highly recommended over adding copious amounts of divs and spans.

Good luck!

5

The main difference is that divs are block elements and spans are inline elements.

Both can be styled using CSS to act however you wish but out of the box you would normally use spans for smaller inline divisions and divs for larger blocks.

Some things will affect inline and block elements different, for example you cannot put a height onto a span element.

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.