Difference between div and span tags

I am quite confused with the functioning of div and span tags. Could anyone give a simple example illustrating the difference between them?

In what circumstances should one be preferred over another?

The div element is by default a block element, whereas a span is an inline element.
Block elements cannot be a child of an inline elements, and some block elements can’t have other block elements as children. So in such cases you may use an inline element, such as span.

Examples:-

<p>This is some text <div class="loud">with part of it styled</div> differently.</p>

^ This is invalid, as <p> which is a block element can only contain phrasing content and inline elements, by default a block will fill the container width and start on a new line, so may break the layout.
So should be:-

<p>This is some text <span class="loud">with part of it styled</span> differently.</p>

The following is also invaid:-

<span class="container">
   <p>Some text here.</p>
</span>

The block element <p> must not be inside an inline element, so should be:-

<div class="container">
   <p>Some text here.</p>
</div>

Both div and span are semantically inert, html5 offers a range of elements that do have semantic meaning which may be more appropriate in some cases. Use these generic containers when you don’t want to imply any meaning. They will generally be used only to hold attributes or force styling.

3 Likes

Think of a span as a inline element, like a anchor or image tag, and think of a div as a block level element like a p or section tag.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.