div vs span (HTML) – What’s the difference?

Beginners learning the HTML and web designing / development often ask the difference between these two HTML tags, especially if they are learning by looking at the HTML code, as they both seem to do the same job of defining a section of HTML code as a class or an ID, which can later be styled using CSS (Hint: CSS is used for the presentation of HTML code).

Here, in this tutrorial, I will tell you the differences between them and which is appropriate for different cases.

div vs span (HTML) – What’s the difference?

div – Document Division Element

<div> tag is used for defining a division or a section in an HTML page as a class or an ID, which then can be formatted / styled with CSS. It divides the page into a section! Consider the following example:

Here, we have defined a class “green-section” with <div> tag. The defined class “green-section” was earlier styled within <style> tag to change the text color to green. Thus, you can see that we used <div> tag to define a paragraph as the one with green text.

Through it, we can separate different sections of a website. For instance, you can define left / right widgets section in your blog with <div>, change the size of widgets, etc. It is generally used with block-level content.

Note that <div> creates a line around the section, so you don’t need to use <p> for the text. Following is its default CSS value:

span – Inline Element

It is used for defining an inline element within a section (i.e., <div> enclosed text, etc.) as a class or an ID. It is used for spanning the element!

Continuing from the previous example, we will now add a <span> tag to define a new element within the <div> defined section to change our text color to blue:

Here you can see that I’ve added a <span> tag to define a new class “blue-text” for changing the text color to blue through CSS. <span> doesn’t create a line around the element, so it is suitable for defining a sub-section of a section. It is normally used to change the property of some text in a paragraph to make it prominent. Infolinks script changes the contextual text to ads through span element.

Note that both <div> and <span> should be used in the places where normal tags (<em>, <strong>, etc.) are not enough. Overusing them can result in an ugly and hard-to-manage code.

Following is the stand-alone example of HTML which you can copy / paste into your text editor, save it to index.html and then open the file in your browser to see its usage:

Conclusion

In this tutorial, I have showed you the difference between these two tags and its appropriate use.
If you have any question regarding these tags or HTML, then why not leave comments in the comments section below so that I can make you happy?