7.1 Span and Div

In the HTML Tutorial we learned how the <span> and <div> tags can be used for grouping HTML elements to make it easier to manage, style and manipulate whole sections of HTML. With CSS this becomes even more exciting and these tags will often be used together with the class and id selectors we discussed in the previous section. These two HTML elements are of central importance with regards to CSS. Refer back to the HTML Tutorial for a full explanation, but basically span is used for grouping inline content within a block-level element (for example, to style pieces of text within a pararaph), and div is used to group one or more block-level elements (for example, to style across several paragraphs of text).

Grouping with span

For example, you may have noticed earlier that any references on this website to tags and attributes are coloured blue and green respectively. To do this, the following code was added to the style sheet:

.tag		{color:blue;}

.att		{color:green}

Then any references to tags and attributes in the HTML documents were wrapped in code like this:

<p>Content text, blah blah, <span class="tag">tag</span>and
 also more text<span class="att">attribute</span>blah blah...</p>

Grouping with div

Say, for example, we had a website on fruit and wanted any lists on apples to be in green and any on oranges to be in...orange. In the HTML document we could have:

<div id="apples">
 <ul>
  <li>Golden Delicious</li>
  <li>Granny Smith</li>
 </ul>
</div>
<div id="oranges">
 <ul>
  <li>Mandarin</li>
  <li>Satsuma</li>
 </ul>
</div>

And in the style sheet:

#apples		{background:green;}

#oranges	{background:orange;}

Note that the above is fine if these lists are only used once in the HTML document. If they are used several times then class should be used (as id is a unique selector and can only be used once in a document). For example:

<div class="apples">
 <ul>
  <li>Golden Delicious</li>
  <li>Granny Smith</li>
 </ul>
</div>
<div class="oranges">
 <ul>
  <li>Mandarin</li>
  <li>Satsuma</li>
 </ul>
</div>

And in the style sheet:

.apples		{background:green;}

.oranges	{background:orange;}

The above are very simple examples applied to text and colors but span and div can do much more than this and can be used to control page layout extensively.