posted by
admin on Wednesday, February 11th 2009 under:
Starting Out Tags:
css,
html
You may have found yourself asking this question before, especially if you’re new to CSS or web development. Don’t worry, you’re not alone - confusion regarding classes and IDs is not uncommon. So, should you use a class or ID selector when developing your CSS? I mean, IDs and classes do the same thing, don’t they? Well, not quite.
On the surface it sure seems that way. Both are used when you want to apply a certain formatting style for specific areas. Both are also style sheet selectors. And both are used when you want to give a certain CSS element a “name”.
However, there are a few differences between the two:
- IDs are only to be used to describe one element, whereas classes can be shared across multiple elements.
- An ID is identified in CSS using a “#”. A Class is identified in CSS using a “.” (full stop/period).
- An element can have multiple classes, but only one ID.
- Only an ID can be called by Javascript’s “getElementByID” functionality.
A simple way to think about this is to draw a comparison with the a general population. Each specific person will have a unique ID, while a class will contain many different people.
ID Explained
W3C gives the definition of the id attribute as “a unique identifier to an element”. In layman’s terms, ID names are only to be used once per page, for a single unique area. This can be especially useful in headers, sidebars, and footers, where the element will only be used once.
First, define your ID in the CSS style sheet as follows:
#firstID{
font-size: 18px;
padding: 15px;
}
Afterward, your HTML content look like this:
<p id=”firstID”>Lorem ipsum dolor sit amet</p>
Keep in mind that technically you CAN define more than one element with the same ID, but it’s not considered best practice to do so. While your page will render properly in most browsers, it will fail the W3C markup validation test.
…continue reading Class And ID In CSS - What’s The Difference?