February 18th, 2008 Posted in webdev | 2 Comments »
I love working with sites designed with CSS and XHTML, but learning and remembering all of the syntax and rules challenges me. When should I use classes and when should I use IDs? What does the HTML and CSS look like when either is chosen?
As a general rule, IDs are meant for elements that happen once per page and classes are meant for elements that happen several times per page. In a practical sense, I think of classes as things like “alertbox”, “code”, “note”, “warning”, “productname”, etc.
Whereas with IDs, they are useful for page layout elements like “header”, “body”, “wrapper” and “box”. They are also useful for the name of a form and anytime you are integrating with JavaScript, IDs are more useful than classes.
I will approach this issue by using this page as an example. In the following paragraphs, I would like to write some code snippets and have them contained by a light grey box with a black border and courier text. Since an ID is used to identify an individual element on a page and I want to have several code snippets on this page, I should use a CSS class.
Classes
Classes refer to elements which will be used throughout the site and in some cases, several times on one page. I like to think of classes as the stylistic elements that are the pillars of the site.
This is HTML for applying a class to a div:
This is CSS for defining a class:
IDs
IDs are used for elements which occur once on a page. Their rules override class rules and can be set up differently on any page, but can only be used once per page. I use them to identify each of my form fields and page divider elements. I could use them for an alert box, as follows, but then I could only have one alert on the page.
This is HTML for applying an ID to a div:
This is CSS for defining an ID: