ID’s and Classes in CSS
CSS beginner’s will love this exploration between the differences and proper uses of the ID and Class selectors.
By Karinne Legault on November 27th, 2008 in Tips & Tricks |
In CSS, you can create your own selectors via ID or CLASS. This is how you apply positioning on certain divs to create the layout of your page. This will also say that a certain area on your page should have a background color that is different from the rest. These are very useful and you cannot create a website without them.
# and .
First off, the syntax. The ID selector is preceded by the hash character (#) while the class selector is a full stop (.).
#branding { .... }
.ads { ... }
And in your HTML you would apply them like this:
<div id="branding">...</div>
<div class="ads">...</div>
Simple enough so far.
One major difference between the two
The ID selector can only be used once in the same HTML document while the class selector may be used multiple times.
Because of that difference, you will notice that in most cases, web designers tend to use the ID selectors for main sections within the site like the header, navigation, content, sidebar and footer.
Difference important for Javascript
If you apply Javascript on your site you MUST follow the rule of only one ID per page otherwise the getElementById function won’t be dependable.
Special functionality
When you create anchors on your page to help you scroll more easily within the document, you use the hash character in the link. Since the ID selector uses that hash character, this mean that you can have a <div id="comments"> in your HTML and get the browser to go directly there with http://www.domain.com#comments. The browser with scroll through the page and find the element matching it. A great reason to use ID’s only once.
Elements can have both
<div id="branding" class="logo">...</div>
This could be very useful in instances where you want to apply a certain style only on a certain page. Let’s say you have a gray box at the top of every page explaining what the page is about but on a certain page you want to draw attention it, so you create a class with a red background instead.
Elements can have 2 classes
That’s right! You can apply 2 classes in the same element. Reasons for doing this are basically the same as using an ID and a class in the same element.
<span class="topbox gray">...</span>
You cannot have 2 id’s in one element
Similar Posts
Want more web design and development tips?
Subscribe to The Web Squeeze by Email, or our RSS feed, and you'll have all the latest web design tips coming right to your inbox! Don't be a stranger, join our forum!




December 20th, 2008 at 9:44 pm
ID’s can act as anchors as well?
Why didn’t anyone tell me this before?