I would like to ask for some simple examples showing the uses of <div>
and <span>
. I've seen them both used to mark a section of a page with an id
or class
, but I'm interested in knowing if there are times when one is preferred over the other.
DIV is used to select a block of text so that one can apply styles to it. SPAN is used to select inline text and let users to apply styles to it.
div
is a block element span
is an inline element.This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.
<div>This a large main division, with <span>a small bit</span> of spanned text!</div>
<div>Some <span>text that <div>I want</div> to mark</span> up</div>
...is illegal.
EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference here for a pretty clear listing. The above is still illegal, as <span>
only accepts phrasing content, and <div>
is flow content.
You asked for some concrete examples, so is one taken from my bowling website, BowlSK:
<div id="header"> <div id="userbar"> Hi there, <span class="username">Chris Marasti-Georg</span> | <a href="/edit-profile.html">Profile</a> | <a href="https://www.bowlsk.com/_ah/logout?...">Sign out</a> </div> <h1><a href="/">Bowl<span class="sk">SK</span></a></h1> </div>
h1
. The userbar, being a section, is wrapped in a div
. Within that, the username is wrapped in a span
, so that I can change the style. As you can see, I have also wrapped a span
around 2 letters in the title - this allows me to change their color in my stylesheet. Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc.
Section 4.4 of the HTML 5 working draft lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is "final" yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE - You need to create one of each element using document.createElement
before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you - a quick Google search turned up html5shiv.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With