January 3, 2008

Classes vs IDs, CSS Practice

Filed under: CSS — Matt @ 4:22 pm

A good use of classes and IDs can save you a lot of time. You’ll end up with a site that’s easy to maintain, and frankly, your code will look a lot cleaner. There are certain rules and practices when using classes and IDs, the following guide looks over them.

First off, what defines an ID and a class? Simply put, an ID is a unique identifier and should only be used once in your document. It’s good practice to use ID on structural blocks of your site such as a wrapper, header, footer, navigation bar, etc. A class can be used more broadly to define objects that can appear multiple times in your document, such as link styling, tables, etc.

Example usage of an ID:

In your html code:
<div id=”mainWrapper”>content</div>

In your stylesheet:
div#mainWrapper { margin: 10px 30px; }

Example usage of a Class:

In your html code:
<span class=”test”>Hello, World</span>

In your stylesheet:
span.test { color: #003366; font-weight: 900; }

When naming your classes and IDs, try and use generic and easy to identify names. For example, instead of calling something “yellowBar” try “topSidebar”. Who knows what color that bar will be 6 months from now! Also, pick a naming style that you’re comfortable with and stick to it - either lowercase (#helloworld) or camel case (#helloWorld) - you should never use spacing in names.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment