CSS Tip: Create a default with special cases Ryan 18 Nov 2005

When you have one element with multiple states, you can use an ID to define the default appearance and classes for the individual cases. This makes your CSS easier to read and reduces code duplication (stay DRY).

In Basecamp, a bar appears below the navigation to display green confirmation messages and red failure messages. The only difference between the two messages is the color and icon.

The basic appearance of the bar is the same in both cases, and there is only one bar, so we can start with an ID. “Flash” is Rails parlance for this sort of message, so we called it #Flash.

<div id="Flash">This is the Flash bar.</div>

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

Flash with no classes

Notice how this default Flash has no color or icon, though the left padding for an icon is present.

Then we defined a class for each special case with a suitable border color, text color, and background.

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

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

Good Flash

<div id="Flash" class="bad">Oh no, something bad!</div>

div#Flash.bad {
  border-color: #c99;
  color: #fff;
  background: url(/images/alertbad_icon.gif) #c00 left no-repeat;
}

Bad Flash

I try to use Defaults and Special Cases as much as I can in CSS because it makes the view, markup, and CSS all easier to read. Here are a few more examples to get your wheels turning:

<div id="Container" class="modal"> . . .
<div id="MessageForm" class="edit"> . . .
<div id="UpcomingActions" class="withlate"> . . .