
Posted on: 28/03/2010
This is one of questions that seems to get asked a lot by those who are just starting to learn how to style html. The answer to it is simply a case of understanding what IDs and classes are and the rest is just down to the judgement of the coder.
Both server the same sort of purpose in that they are purely to dictate the styling of an element through css. Think of them almost like a blank canvas, by themselves they add no real value to the html as the have no default properties built into them, but start styling them through the css and it will create something magical.
A class is most commonly used to apply the same declarations to multiple elements. A useful aspect of a class is that multiple classes can also be used within one element like so:
<div class="blue"></div> <div class="blue"></div> <div class="blue small"></div>
An ID is used to uniquely identify an element, so because of this it can only be used once within an html document. Also unlike a class you cannot use multiple ID’s within an element, you can only use one per element.
Also you don’t need to select one or the other as both can be used within an element. For example say that you needed to uniquely identify some elements but they were all going to be styled the same, nothing is stopping you from doing this:
<div id="post1" class="posts" ></div> <div id="post2" class="posts" ></div> <div id="post3" class="posts" ></div>
While ID’s and classes have no differences within the css, as you can style them in exactly the same way, they do have a difference within the browser itself. A class is quite meaningless, while an ID does have some meaning and is one of the reasons behind an ID’s need to have a unique name.
A browser can use an ID as an anchor point within a page and scroll to that ID if the url tells it to. Have ever noticed a url that looks something like this http://webdesignpond.co.uk/#tips and you have ended up halfway down a page instead of at the top? That is because the browser has been told to locate the ID and go to that location, in this case the id called tips, and this is all thanks to the ID having a unique name and also the hash used within the url.
So as I said at the beginning it is just down to having a little bit of knowledge about what the differences are between classes and IDs and judging for yourself if an ID or a class is better suited within the elements you are coding.
4 Comments
Great post. I think a common mistake made by developers is using classes when IDs are supposed to be used.
yeah, that and using a class or ID when neither is really needed…but nesting is for another day
Great info for me, I hate reading manuals that go all around the houses to explain something. Go to the top of the class (pardon the pun) Dizi.
Regards
Linsky
Thanks Linsky, I’m happy that this was of use to you