[thelist] I've found a great use for <span>

Simon Willison simon at incutio.com
Thu Aug 1 09:02:01 CDT 2002


I've found a great reason to use <span> - providing content to browsers
that will not display CSS. Here are two examples.

Example 1: A Site logo graphic.

Say the main header logo of your site is a pretty image with text in it.
You could display the image straight on the page with an alt tag - a
perfectly valid and reasonable technique. However, the text of the logo
really deserves to be marked up as <h1> as it is the first and most
important header on the page. Also, the image itself is more of a
presentation thing than a document content thing. Here's my solution:

<h1 id="logo"><span>My Groovy Website</span></h1>

And the accompanying CSS:

h1#logo {
   display: block;
   width: 150px; /* Width and height of your logo image */
   height: 50px;
   background-image: url("logo.gif");
}
h1#logo span {
   display: none;
}

CSS supporting funky visual browsers will display the logo image. Anything
that only cares about the HTML document will recieve an <h1> tag containing
the logo text.

Example 2: A horizontal menu

Here we want to create a horizontal menu with a number of options in it. We
want these options to have funky hover over effects, backgrounds, borders
and generally look nice. In browsers that don't support CSS we want them to
be seperated by pipes (this is also an accessibility issue - Bobby at al
get annoyed if you have links with nothing seperating them apart from blank
space). Here's the HTML:

<div id="horizontalMenu">
<a href="page1.html">Page 1</a><span> | </span>
<a href="page2.html">Page 2</a><span> | </span>
<a href="page3.html">Page 3</a><span> | </span>
<a href="page4.html">Page 4</a><span>
</div>

And here's the CSS:

div#horizontalMenu a {
   display: block;
   float: left;
   width: 10em;
   background-color: #f00;
}
div#horizontalMenu a:hover {
   background-color: #ff0;
}
div#horizontalMenu span {
   display: none;
}

This will give you funky hover effect block links next to each other in a
browser with good CSS support, while browsers without CSS will display a
bunch opf links on the same line separated by pipes.

It could be argued that a more logical way of marking up the above would be
to use an unordered list - unfortunately doing so can lead to problems with
IE5 which doesn't seem to like it when list items are turned in to block
items (or something like that).

Conclusion

<span> has a use! I don't think there is any other tag that would make as
much sense for the above tasks.

You can see both of these techniques in effect here:
http://development.incutio.com/lums/ (my first attempt at recoding
http://www.lums.lancs.ac.uk/pages/Executive/ in XHTML and CSS)

Regards,

Simon Willison
http://www.bath.ac.uk/~cs1spw/blog/




More information about the thelist mailing list