Divs, Spans, id and class Attributes
The great organizers and grouping mechanisms of HTML are the <div> tag and the <span> tag. Up to this point, the distinction between inline and block elements has been glossed over for the sake of simplicity. But to use the <div> and <span> tags properly, knowledge of block and inline elements is crucial.
The simple story is, block elements take up a “block” of space - they are elements like the <p> tag, the <table> tag, and the <ul> tag. Then, there are inline elements, which fit into the flow of character on the page - this includes the outdated <b> and <i> (bold and italic) tags, and the <em> emphasis tag. One tag that is somewhere in between is the <img> tag, which is an inline-block element - it fits into the flow of text like an inline element, but has a specific height and width like a block element.
<div> tags are the block version of an organizing element, and <span> tags are the inline version of an organizing element. They are used to create structure in your document, especially for the purposes of page layout, when combined with CSS.
One of the key components of styling using CSS is the “id” and “class” attributes. The “id” attribute is a unique attribute that only one element should have, and it allows CSS to style that element specifically. In contrast, the “class” attribute can be attached to an unlimited number of elements, and CSS rules will style all of them.
Here’s a typical example of using <div> and <span> tags, along with id and class attributes:
<div id=”container”> <div class=”items”> <ul> <li>This is item number <span class=”number”>1</span></li> <li>This is item number <span class=”number”>2</span></li> </ul> </div> <div class=”items”> <ul> <li>Item number three</li> </ul> </div> <div id=”footer”> This is the footer. </div> </div>
In this example, the outer div with id=”container” can be styled with CSS, without styling other <div> tags. Likewise, the footer <div> can be styled independently of other <div> tags. Meanwhile, the two <div> tags with class=”items” can be styled with a single set of CSS rules, due to their shared class.
The <span> tag is used here to wrap the numbers, perhaps to provide special styles for the numbers - bold, or perhaps a larger font size - the possibilities are endless.