Create CSS class and id names to identify divs and other page elements for formatting. Builder.com columnist Michael Meadhra shares his thoughts on emerging naming conventions.
When you’re working on a Web page and need to come up with an identifying name for a div, the natural temptation is to use a name that describes the element’s page location. This approach leads to class and id names such as the following:
These are all valid names for CSS and XHTML classes and ids. They’re simple and descriptive, so they serve the purpose of identifying the page element and its corresponding CSS style.
The problem is that such names relate to a specific presentation of the content. They reference the position of page elements in a particular page layout, and may be inappropriate and confusing outside the context of that layout. And, these names don’t say anything about the structure of the document content. There are better ways to name your CSS classes and IDs.
True structural markup means completely separating presentation/position information from the content—that includes class and id names that appear in the markup.
The goal is for all markup to relate information about the document’s structure rather than its presentation. This facilitates reusing the content and markup in different presentation formats by simply changing the CSS. When you think about it, it’s easy to see that class and id names that refer to page position are inappropriate in presentation formats such as audio. Therefore, structural naming names classes and ids by their purpose in the document, not their location.
Taking a structural approach to naming might produce class and id names such as the following:
These names are just as descriptive as the presentational names, but they describe what the page element does, instead of its location. The result is code that is much closer to the goal of pure structural markup that designers can format for various presentation media without changing the markup.
Even if you don’t plan to format your Web page for presentation in other media, using structural naming can help make future updates/redesigns easier. For example, structural naming eliminates the confusion that would arise if a div with the id right-column moves to the left side of the page. Naming the div sidebar is much more appropriate, and the name remains valid no matter which side of the page it’s on.
Andy Clarke looked at the code of 40 Web sites by builders with reputations for espousing standards-compliant Web design. Although class and id names were far from uniform, some common names did show up frequently. Here’s a sampling of the most common class/id names: