Monday, October 4, 2010

Combining IDs with Multiple Classes

Classes are especially useful when you wish to have control over a number of elements. Consider
the following drinks list, the source code for which is available in the drinks.html file:
<ul id="drinks">
<li class="alcohol">Beer</li>
<li class="alcohol">Spirits</li>
<li class="mixer">Cola</li>
<li class="mixer">Lemonade</li>
<li class="hot">Tea</li>
<li class="hot">Coffee</li>
</ul>
Note first that the unordered list (<ul>) is given a unique ID. Thus, id="drinks" will not be
used again on the page at any time, allowing that particular list to be styled uniquely. Note also
that Beer and Spirits are within list elements defined with class="alcohol", Cola and Lemonade
are within list elements defined with class="mixer", and finally Tea and Coffee are defined in
list elements with class="hot". This allows each drinks group to be treated individually.
The CSS declares that the default text for that list will be red, so any list items without a
class attribute will default to red text:
/* Drinks list styling */
ul#drinks {
color:#F00;
}
Next, the classes for each drink type are defined with unique shades of gray for font color:
/* Define alcohol color */
.alcohol {
color:#333;
}
/* Define mixer color */

.mixer {
color:#999;
}
/* Define hot drinks color */
.hot {
color:#CCC;
}
The result sees the list of items move through shades of gray (defined by the classes).
Any further drinks added to the list can be assigned to a particular drinks group, such as
<li class="alcohol">Wine</li>. Thus a logical color key is established using simple CSS classes.



**■Tip Before adding a class to an element, be sure that the element needs it. Too often web designers
overuse classes when the (X)HTML is already providing more than enough hooks for the CSS. Make sure that
the element cannot be targeted using a descendant selector or other method before opting for a class. This
will help keep your code lean and make future redesigning much easier.

No comments:

Post a Comment