The Difference Between <div> and <span>
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 ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.