Div and span, practical differences

These two tags are containers which are intended to structure the content, but have a complementary role and rendering rules that differ.

Span is used primarily to associate a style to a part of a text while div is used to organize the layout of the page.

Both tags must have a start and end tag, the reduced form is not supported, of course.

Not valid for example this:

<div class="xxx" /> // not valid

The only valid format is this:

<div class="xxx"></div>

The tag may be empty.

Div

The <div> tag is a block-level element, so a rectangular object which can not be broken over several lines.
It has the attributes margin, padding, width, height.
It is preceded and followed by a newline.

For example, the following text:

<div>0000000<div>111111</div>222222</div>

appears as follows:

0000000
111111
222222

Span

The <span> tag is a inline element, it fits into the flow of the content and can be distributed over multiple lines.
We can not specify a height or width or surround it with a margin.
It can be placed inside a paragraph to define a part of it without affecting the appearance of the text.

<span> does not add linefeed and the following:

<p><span>0000000<span>111111</span>222222</span></p>

appears as follows:

0000000111111222222

Margin

It is not possible to add a outer margin with the margin attribute.

<p>
<span style="border:1px dotted black">0000000
<span style="margin:8px;background:green;">111111</span>
222222</span>
</p>

appears as follows:

0000000111111222222

On Internet Explorer (before IE9), the margin is displayed vertically and horizontally.
On Chrome and Firefox it does not appear, according to the standard.

Without the margin it appears as follows:

0000000111111222222

Height and width

The width and height attributes are recognized by IE before version 9 but have no effect in Firefox and Chrome and should be forgotten:

<p>
<span style="border:1px dotted black">0000000
<span style="height:32px;width:100px;background:green;">111111</span>
222222</span>
</p>

0000000111111222222

Padding

<p><span style="border:1px dotted black">0000000
<span style="padding:8px;background:green;">111111</span>
222222</span></p> 

0000000111111222222

We see that the margin is effective on all web browsers.

More information

© 2010-2012 Xul.fr