All Posts Tagged With: "html"

CSS Tip: Assigning Multiple Classes to a Single Element

The 37signals team wrote up a nice trick on creating a default styling for an element using an element id and then customizing it using an element class.

Here’s one of their examples:

#Flash {
  text-align: left;
  border: 1px solid #ccc;
  font-size: 14px;
  margin: 0 7px 12px 0;
  padding: 5px 5px 5px 30px;
}

div#Flash.good {
  border-color: #9c9;
  color: #060;
  background: url(/images/alertgood_icon.gif) #E2F9E3 left no-repeat;
}

<div id="Flash" class="good">Oh yes, that's nice!</div>

This technique is nice when you have one specific element that needs decorating. Since element ids are unique within a document, you can apply the exact formatting you need to that one section. However, you need to define an explicit CSS block — div#Flash.good in this case — each time you wish to combine styles.

A similar approach is assigning multiple classes to the same element:

.Flash {
  text-align: left;
  border: 1px solid #ccc;
  font-size: 14px;
  margin: 0 7px 12px 0;
  padding: 5px 5px 5px 30px;
}

.good {
  border-color: #9c9;
  color: #060;
  background: url(/images/alertgood_icon.gif) #E2F9E3 left no-repeat;
}

<div class="Flash good">Oh yes, that's nice!</div>

Use this to compose more general styles. For example, if you want all error text to be red and bold, you could define a general error class. You can then use that style anywhere in the document with any other style without needing to update your CSS.

Nothing too earth shattering, but two good tools to have in your bag.