Coding with Jesse

Context-Sensitive Class Names

July 26th, 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 class="main">
    <h2 class="title">Main Title</h2>

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: { color: blue; background: white } { 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.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!