(

The Promise of CSS


The goal of CSS is the separation of style from content. Before CSS was available, the only way to stylize HTML content was to use HTML tags and attributes, like <font> and color="red". This is no longer considered good practice.

You may be using CSS, but if changing the style of an existing HTML document means you have to make changes to the HTML, then you have not achieved separation of style from content. The key to this separation is to choose good HTML tags and good class names in the first place. The benefit is that style changes require code change in only one area of the codebase (stylesheet), not a multitude of areas (HTML documents). It is much easier to keep track of one thing than many.

Achieving this goal completely may be impossible, but moving towards the goal will still yield valuable benefits. It requires skill-building and a learning curve.

To accomplish this goal, follow these two guidelines:

  1. Use tags judiciously to demarcate types of content.
  2. Choose tags and class names that classify the content, not the style.

Here’s an example that fails to meet that goal:

<div>
  <strong>Title:</strong>
  Clymb
  <br>

  <strong>Date:</strong>
  4/2/2012
  <br>

  <strong>Type:</strong>
  Company
  <br>
<div>

The problem with this example is if you wanted to stylize the label:value pairs such that each pair has a background color, and has top and bottom margins, what would you do? Or what if you wanted to stylize the value separately from the label? You couldn’t easily do that without substantially changing the markup.

Here’s the refactored markup and stylesheet:

<ul class="label-values">
  <li>
    <label>Title:</label>
    <span>Clymb</span>
  </li>
  <li>
    <label>Title:</label>
    <span>Clymb</span>
  </li>
  <li>
    <label>Type:</label>
    <span>Company</span>
  </li>
</ul>

<style>
  .label-values > li { background-color: #eee; margin: 3px 0; }
  .label-values > li > label { font-weight: bold; }
  .label-values > li > span { font-family: monospace; }
</style>

There’s a little more code in this example, but the markup is much more semantic, and therefore easier to stylize. The <li> tags correctly identify each value:label pair as a list item. The <label> tags correctly identify the labels. The <span> tags identify the values. Unfortunately, HTML doesn’t give us anything more specific for values. But CSS selectors are often powerful enough to overcome this limitation without the need to assign classes. Now, we have CSS styles defined for a flexible, general-purpose component that can be used elsewhere in the application.


blog comments powered by Disqus
(