A good buddy of mine has recently started his own learning process diving into HTML, CSS, and Javascript. He came to me with a question recently wanting to know what the actual difference was between a class and an id, and when each should be used. As I explained this to him I thought that this would make a great post as I am sure that he isn’t the only one who has wondered this.
First off let’s cover exactly what the point of a class or an ID is. HTML has a wide array of different elements that describe the content on your page in a very general sense. For example you have <p> tags for paragraphs, <ul> tags for un-ordered lists, and so forth. ID’s and Classes let us further differentiate the various elements within our website such as our page header, navigation menu, footer menu, sidebar, etc. We can then utilize these within CSS to style those specific sections; or to alter them with the use of Javascript.
So, what’s the big difference? Well for starters classes aren’t unique; while ID’s are. You cannot utilize the same ID across more than one element within a page, however you can apply the same Class to multiple elements, and you can apply multiple classes to a single element. Let’s take an example. Assume we have a series of elements within our webpage that we wish to align to the left side. We can accomplish this by creating a left class in CSS and applying it to our different elements:
.left { float: left; }
Some content
Notice that we can then apply the left class to various elements within our website – successfully aligning any element we need to the left.
Now if you notice we also have an element with the id of dynamicContent specified. ID’s, as mentioned earlier, must be unique. As such we can only apply a single ID to an element at a given time, and we can only use the same ID once per page. In practice you might accidentally end up using the same ID more than once, and you may not notice anything breaking because of this – however you’re website will fail validation if you ever test it.
Next up is another huge difference between an ID and a Class. ID’s can be utilized in the same way that a link anchor. So if our code above was placed on a page named page.php we can then link directly to the content area with the following URL:
page.php#dynamicContent
Finally JavaScript coders will often utilize the getElementById function to modify a specific website element. This function does basically what it sounds likes – it selects an element from the website by it’s ID, and this function isn’t very reliable when you have multiple elements with the same ID.
Hopefully this outlines the difference between Classes and ID’s. If anyone still has any questions feel free to post them in the comments below.
Leave a comment