Both <div>
and <span>
elements are types of containers,
but with some different qualities. By default, a <div>
element has infinite width (at least
to the browser edge), which can be seen by applying a border to one, like
this:
<div style="border:1px solid green;">Hello</div>
A <span>
element, however,
is only as wide as the text it contains. Therefore, the following line of
HTML creates a border only around the word “Hello,” which does not extend
to the righthand edge of the browser:
<span style="border:1px solid green;">Hello</span>
Also, <span>
elements
follow text or other objects as they wrap around, and can therefore have a
complicated border. For example, in Example 18-2, CSS has been used to make the
background of all <div>
elements
yellow, to make all <span>
elements cyan, and to add a border to both, before then creating a few
example <span>
and <div>
sections.
<!DOCTYPE html> <html> <head> <title>Div and span example</title> <style> div,span { border :1px solid black; } div { background-color:yellow; } span { background-color:cyan; } </style> </head> <body> <div>This text is within a div tag</div> This isn't. <div>And this is again.</div><br /> <span>This text is inside a span tag.</span> This isn't. <span>And this is again.</span><br/><br /> <div>This is a larger amount of text in a that wraps around to the next line of the browser</div><br /> <span>This is a larger amount of text in a span that wraps around to the next line of the browser</span> </body> </html>
Figure 18-4 shows
what this example looks like in a web browser. Although it appears only in
shades of gray in the print version of this book, the figure clearly shows
how <div>
elements extend to the
righthand edge of a browser and force following content to appear at the
start of the first available position below them.
The figure also shows how <span>
elements keep to themselves and
only take up the space required to hold their content, without forcing
subsequent content to appear below them.
For example, in the bottom two examples of the figure, you can see
that when <div>
elements wrap
around the screen edge they retain a rectangular shape, whereas <span>
elements simply follow the flow of
the text (or other contents) they contain.
Since <div>
tags can only
be rectangular, they are better suited for containing objects such as
images, boxouts, quotations, and so on, while <span>
tags are best used for holding
text or other attributes that are placed one after another inline, and
which should flow from left to right (or right to left, in some
languages).