Multiple classes

Why didn’t anyone tell me you could apply more than one class to a HTML element? I guess I didn’t think to ask.

Dave Shea of Mezzoblue mentions this jewel in his post Positioning and the Cascade

You can apply a bunch of classes to a single element.

Just when I was beginning to think I had the basic nuts and bolts of CSS worked out – something like this comes up. It astounds me that this slipped me by. On reflection there’s a good chance I read it early on – well before I could imagine the use of more than one class on an element.

A use I can see for multiple classes is in a navigation menu where one or more of the items needs a selected or on-state to be indicated, and you wish each menu item to be individually styled. In the past to do this I have applied unique IDs to each of the links in the menu and applied a class to indicate the onstate.

<ul>
	<li ID="nav1">
		<a href="#">Item 1</a>
	</li>
	<li ID="nav2" class="on">
		<a href="#">Item2</a>
	</li>
	<li ID="nav3">
		<a href="#">Item 3</a>
	</li>
</ul>

This is a reasonable solution. The IDs allow each element to be styled uniquely, perhaps a different background image in each; And the class can be easily used to indicate the onstate – a change of colour or weight of text. Unfortunately this approach has come unstuck.

.Net has entered the scene at work in a big way. This is mostly great and is encouraging a wonderful modular approach to site building, sadly it makes control over the IDs of elements very awkward. So instead of using an IDs for the unique elements I have been using classes. Ignorantly thinking this would displace the possibility of using a class to indicate an on-state on the same element I have applied it do a different nested element.

For example, on the ‘A’ instead of the ‘LI’:

<ul>
	<li class="nav1">
		<a href="#">Item 1</a>
	</li>
	<li class="nav2">
		<a href="#" class="on">Item2</a>
	</li>
	<li class="nav3">
		<a href="#">Item 3</a>
	</li>
</ul>

This will still provide a number of useful styling options on the ‘A’ but the ‘LI’ of the ‘on’ menu item cannot be singled out.

What I learnt today is that you can simply do this:

<ul>
	<li class="nav1">
		<a href="#">Item 1</a>
	</li>
	<li class="nav2 on">
		<a href="#">Item2</a>
	</li>
	<li class="nav3">
		<a href="#">Item 3</a>
	</li>
</ul>