• Context-Sensitive Class Names

    Jul 26 2006

    Usually when assigning class names, it's most natural to assign a different class name to each uniquely styled area of the page. Often, there are common words you'll want to use as class names in more than one spot on the page such as 'date', 'section', 'title', etc.

    At first, it seems the solution is to make up unique class names like 'header-date' and 'comment-date' or 'side-section' and 'main-section.

    Instead of doing this, you can just stick to using your simple 'date' and 'section' class names but refer to them in their context. For example, if your mark-up looks something like this:

    <div class="side">
        <h2 class="title">Side Title</h2>
    </div>
    
    <div class="main">
        <h2 class="title">Main Title</h2>
    </div>
    

    Then you could define your CSS like so:

    .side .title { font-size: 1.2em }
    .main .title { font-size: 2em }
    

    Even better, you can get rid of the unnecessary class names and just define styles onto elements within different sections of the page:

    .side h2 { font-size: 1.2em }
    .main h2 { font-size: 2em }
    

    You also have the option of doing element-sensitive definitions. Perhaps an <h2> tag with a 'date' class can mean something different than an <h3> tag. Then, just do this:

    h2.date { color: blue; background: white }
    h3.date { color: green; background: red; }
    

    This is pretty simple stuff, but it opens up all sorts of possibilities for keeping your HTML as clean as possible. Just be careful not to get confused (or confuse others) by using the same class name for more than one purpose.

  • Comments

    Commenting is now closed. Come find me on Twitter.