George’s Wonder Blog

Just another WordPress weblog

CSS: Use ID Selector or Classes?

March 19th, 2008 by George

When should you use an ID Selector or a class in CSS?

There are many of answers, some more technical than others, but here’s a fast and dirty answer.

Use an ID selector when it will be used only once on the page. For example, DIVs for header, body and footer are just begging to be ID selectors.

Use a Class name when an element will be used more than once on a page. As an example, if you have styles for external links and a different style for internal links you should use a Class name.

SAMPLE: What it Looks Like

<html>
<head>

head code here
</head>

<body>

<div id=”header”> Header stuff here </div>

<div id=”content”> Page content here including an <a href=”something.html” class=”ilink”>internal link</a> and an <a href=”http://www.somewebsite.com” class=”elink”>external link</a>. </div>

<div id=”footer”> Footer stuff here </div>

</body>
</html>

del.icio.us Digg Facebook Technorati StumbleUpon Bloglines Ask

This entry was posted on Wednesday, March 19th, 2008 at 7:44 pm and is filed under Web Design. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 responses about “CSS: Use ID Selector or Classes?”

  1. Eyebee said:

    I was always of the understanding that you can (or at least should) only use an ID once on a page anyway.

  2. George said:

    Exactly. As a matter-of-fact if you have two elements on the same page with the same ID name you will end up with a conflict only one of them will be styled as you specified. I guess depending upon the browser maybe neither wold work if you used an ID 2x or more.

Leave a Reply