Frequently while spying on others' CSS files (it's the best way to learn – really!) I'll notice a distinct difference between the frequency at which they use ID selectors versus Class selectors. I've always leaned toward using class over id in my CSS, but never for a good reason.
Today I decided to look up the difference between class and id and learned quite a bit in the process. Both Evrsoft and css-discuss provide very useful information on the subject, and they both distinguish the difference between class and id as follows:
The key thing to know is that IDs identify a specific element and therefore must be unique on the page – you can only use a specific ID once per document. Many browsers do not enforce this rule but it is a basic rule of HTML/XHTML and should be observed. Classes mark elements as members of a group and can be used multiple times, so if you want to define a style which will be applied to multiple elements you should use a class instead.
As it turns out, I've probably been better off all along by sticking to my class over id mentality. However, it's good to know that id has a specific purpose. Hopefully now I'll be able to use both selectors correctly when they are appropriate.
Comments
For all the problems I had with CSS early on, this was one thing I understood from the get-go (I must have read it somewhere). I find it very interesting that you, with all your 1337 CSS skillz (tableless tables!!!!) didn't know this difference.
Also, it is of interest to note the the id tag is used extensively in JavaScript, and it can be used to reference a place on a page (as in, "item.php?id=416#comments" (Bernie in this page uses "<a id="comments"></a>"... but this to me seems to be wasteful. More concise would be to replace "<h4>Comments</h4>" with '<h4 if="comments">Comments</h4>').
Just my $0.02
Ryan,
I think you give me more credit than I deserve. I'm learning new things about CSS all the time.
As far as your page anchor idea goes, XHTML requires that anchors be driven by the a tag and its id attribute. You can't (yet) specify an id for any arbitrary element and expect UAs to direct you to that "anchor" on the page.
See the bottom of this page for more information.
sa
hii
i jus was wondering the difference b/w css and id... and whn searched on google..thiis was a fantastic piece of explanation... ..thanx..
Bye
Anitha
Thanks!
I found this page trying to alter CSS dynamically.
'
And I so needed the function getElementsByClass - found some implementations.
But really I am interested in altering CSS on the fly.
Ideas?
Henrik
Just what i was looking for :)
Thanks Bernie :D
Could you give an example of when you would ever really use id over class? I mean, id is limiting, while class is not. I understand what the difference is, but you could do everything about css not ever using id.
Basically what is the id's big selling point, and why does it even NEED to exist?
Mark, if you ever do any JavaScript programming you'll quickly see why id is important. There is an extremely useful function called getElementById() that, as you might guess, lets you get a handle on a page element by its id, and not by its class. There are other reasons, I'm sure, but this is probably the most notable one in my mind. I hope that helps.
Mark, another reason to use id is that an element can have both a class AND an id. Since id is more specifiic, CSS rules will generally overrule the class for that. For example, I've done something like the following:
<div class="tab" id="tab1">Tab 1</div><div class="tab" id="tab2">Tab 2</div>
Then in my css i can do
div.tab { background-color: #F00; }
div#tab1 { text-decoration: none; }
In other words, it provides a way of having something belong to a group but also having it be unique. I also consider using class when there is only one instance to be bad style, though I do not know if this is generally held or not.
Then there are the huge advantage of id when using JavaScript that Bernie mentioned, and I also mentioned in my first comment, in case you missed it :-).
Thanks a lot. I came across this specifically seeking the information. Thanks for teaching me that little tidbit :)
Good article, solved a problem. keep it up!
Funny,
I'm learning CSS as I'm designing a website; come across a chapter that uses 'ID' and wondering why the author didn't use 'class' instead. Googled for the difference. Found this website as the first link :)
Thanks for the info.
Specifically, the author used 'ID' to help with the site layout:
<div id="header">, <div id="content"> etc. I guess since it will only be used once per page, its good form eh?
Found this link on Google searching for the difference between id and class, great answer and good information in the comments too, thanks.
Great post. I was actually wondering abt the ID Vs. Class in css. Once question though that i have is that if i have a scenario like this.
#intro
{
background-color:#FFFFFF;
font-size:#10px;
margin:0px;
}
.introText
{
background-color:#CCCCCC;
font-size:#16px;
margin:5px;
}
and then have a div as such
<div id="intro" class="introText">
Hello world!
</div>
Does the ID definition overule the class def. When experimenting with different browsers i've got different results as to how this is interpreted.
Yusuf, scroll to the bottom of Advanced CSS and you'll see a section on overriding that says the following:
...you can override this aspect of the CSS by putting further style definitions closer to the affected text than the class that defines it. We'll call this "overriding by proximity," because that sounds cool.
So it sounds like the best rule of thumb to remember is, the farther away the rule, the less precidence when evaluating style.
Cheers! Just in time too! -- I was about to switch from using class to using id more often because I felt that I was using it the wrong way around. As it turns out, I wasn't!
Thanks,
Reached here from googling 'css id class difference' :-)
All this time, i was using ID's more thinking that ID is a subset of CLASS. And today, you changed my way of designing!
Thanks
Vijoy~
Like many people who posted here, I did a search on what the difference is between id and class in CSS, and this page came up. Thanks a lot for the information and discussion!
thankyou :)
Gr8 Information, and Very rarely available too, Comments also teach !!! Must See :-)
found this site with a google search on the subject like everyone else! Very helpful.. I am learning CSS right now and havent started designing yet. My question is I will not be designing a site that will have alot of repeated styles there will be alot more unique stuff. Its my portfolio site. It wont have much text really.. so wouldnt I prob be using ID more than class?
I still got ALOT to learn!
Just what I was looking for!
As everyone else seem to have done, I Googled here too ;-)
Cheers!
Great site.
I forgot about this subtle diiference and your site helped me mentaly re-allign this concept.
Best!
thx for article :)
This is a relatively old thread, so I hope people are still checking it out.
For JavaScript programming, I see the benefit of using the ID directive. However, I still do not see the benefit of using ID as the identifier for setting style.
The main arguments that I've seen are (1) "It's good form to use ID if the element exists only once on a page", and (2) "You can use CLASS to override some of the elements of the ID definition (inheritance, if you will)".
The "good form" argument doesn't make sense to me because it is too limiting. If at a later time you decide to add a section to a page that has the same formatting as your previously "unique" section, good form dictates that you can not use the existing definition unless you change it to a class (which would require you to change every page in your site which accesses that style definition).
The "inheritance" argument makes a little more sense but the same thing can be accomplished by using CLASS and then using inline styling on the elements that you wish to override.
Are there any real "compelling" reasons for using ID rather than CLASS for style definitions?
Thanks for clearing this doubt . Worth a Google Bookmark+Stumbleupon+Digg :)
I have programed in VB6 for years, but have just started with HTML and CSS. On some abstract level I understand the above description of the difference between id and class, but I think it might make sense on a practical level if I could see both in correct use somewhere. Can anyone recommend a good website for the newbie trying to figure out the ins and outs? I am not in any position to know if the source I see on various websites are good or bad examples.
Thanks,
Glenda
Oh nice, I was wondering what it was all about, to me they seemed to do the same job but now I understand.
Good post!
these threads continue to be useful months or years after they are written....thanks for the great sharing of information.
cheers
mike
Thanks for sharing of information.
This is an old thread but very useful, thanks for sharing guys!
One more thing i want to tell is.....If a class and ID has the same property say background colour defined in both of them differently
ex: .class_name { background color : #ff00ff; }
#id_name { background color : #00ffff;}
and....if they are applied to the same tag or element in HTML/XHTML, then the id takes the precedence......it means the background color property from the id will be applied to that element even though that element has already a class associated with it.
hey thanks learned lots!!!!!!!!!!!!
Awesome topic, found it after googling too.
(always used ID's)
Researched some and came back to add.
I don't think you should consider it class 'VS' id's, for which is better.
Below code shows, imo, decent use of class and id's.
Combining could lead to nice coding style too.
HTML:
<div class="something">
<div class="something" id="specific">
Whatever
</div>
</div>
file.css:
.something { style:value;}
.something#specific { more/adjusted-style:value;}
Seems to work well crossbrowser too.
Like most I've been saved, cos now I really understand the different between CSS Id and Classes.
Thanks for making this much clearer!!
Great everyone for their ideas. Im reasonably new to CSS, being self taught - like most I suspect.
I always used ids as a template of sorts, being unique on a single page. ie. header, navbar, content, footer etc.
Where main elements such as layout, positioning, style, backgrounds etc were fixed for that id. Classes were then used to modify all the smaller, variable things within any id.
However, I like Lenny's post.
Although it's roughly the same concept, it flips the id and class selectors, and in some way makes better sense, and possiby more in line with the designers of CSS possibly.
A class defines things in a bigger more general sense, (a class of children) where id is more of a smaller and specific thing. ( a single child)
Now, all I have to do is settle on one standard....Urghh!
I'm sure in time it will crystalize.
Great blog...Cheers!
Who are you people? If you don't know the difference between class and id, there is a document describing things like this. It is called the CSS SPECIFICATION. Reading the specs...what a concept.
Here is the answer to this aspect of CSS:
http://www.w3.org/TR/REC-CSS2/selector.html
Remember, "Coward," the W3C specs are more intended for user agent developers than they are for web designers. I'm not surprised that the less technically inclined have had to look elsewhere for a decent explanation of the difference between the two attributes. Sometimes you just can't beat laymen's terms.
Thanks for the post.. I've done the exact same thing, never really understood the difference so I chose to go with classes (sadly because .class is a lot cleaner than #class which makes it easier for me to read). I suppose now that I know though I'll start using div ids for my layout and classes for my content for "correctness."
Coward -
Search engines have revolutionized the internet in such a manner that people no longer need to spend X minutes / hours / days pouring over manuals generally written by people that *don't* want to write them. What difference does it make whether I waste time reading when I can go up to my fancy little search bar on my browser and type "difference between div class and id." Just because *you* do something a certain way, doesn't mean that everyone should. If you maintain that mindset, you'll learn miss a lot in life.
Thanks for the article,
Chance
Good all round article, Ive just finished my CIW course work and am awaiting my exam dates. 4 years of work over and I was never formally introduced to the difference between ID and Class -
"Im going with ID's for layout and classes for content..."
doesnt realy work in a 'standards' sense, since you may for example, have a relatively placed div element which will be replicated down the page, ie: have the same style applied, this is a "layout" element and therefore ( by the above statement ) should be id, not class... this would cause a parser error ( and the browser probably ignore the error, render perfectly well. or ignore the id altogether, depending on the browser ).
Ok, so in a nutshell, does it matter ?
I'd say no... and it realy depends on if your a sloppy coder or a perfectionist ( I'd say most people like to use tab spaces in notepad and make their code easier to read and more understandable )...
so if you want clean code, consider this:
You look at a css document, which happens to be full of class selectors ( .foo {} .foo2 {} ... ) your first question will undoubtably be, how many elements are these class selectors actually affecting, and then searching the body of the document to find them all, whereas if you use #foo {} #foo2 {} ... then you already know that all ID selectors are only affecting one element, and all Class selectors are affecting multiple elements. ( Id say in most designs there are more times you would ID over class, with the above in mind that is, thus making your code that little bit cleaner and understandable )
Just my 2.c, Im sure there are multiple 'personal standards' that people use, such as mentioned above ( which is my personal favourite:
<div class="something">
<div class="something" id="specific">
Whatever
</div>
</div>
file.css:
.something { style:value;}
.something#specific { more/adjusted-style:value;}
technically isnt perfect as any ID can only be used once in the entire body, but would be fantastic if the same ID could be used multiple times in the document body. ( Id realy like to see this concept catch on and maybe get something like a child class such as <div class.class1="one" class.class2="two"> or something similar to that...
and then ".class2.two {}"
would be handy...
Hi,
i have completed one assigement of css.It is working properly in IE(internet Explorer)when i have tried into firefox it is not working properly.what is the solution please tell me.I have sent my code with this file.
Following is the code
body
{
margin-bottom: 20px;
margin-left: 70px;
margin-right: 70px;
margin-top: 20px;
background-color: Black;
font-size: 12pt;
font-family: Verdana;
}
#header {
height: 8px;
padding: 0 0px 0 0px;
background-image: url(images/head_1.bmp);
background-repeat: repeat-x;
width :825;
height:85;
}
#header h1 {
padding: 10px 0 0 0;
margin: 10px 0 0 0px;
color: #FFFFFF;
margin-left: 10px;
margin-bottom: 10px;
}
#slidebar {
float:left;
background-image: url(images/LH2.bmp);
width: 243px;
height:210px;
border-bottom : 2px solid black;
BORDER-RIGHT: 0px solid;
}
.LogoMargin
{
margin-bottom:10px;
margin-left:20px;
margin-right:20px;
margin-top:20px;
}
.LogoMarginbody
{
margin-bottom: 20px;
margin-left: 70px;
margin-right: 70px;
margin-top: 20px;
background-color: Black;
font-size: 12pt;
font-family: Verdana;
}
#LeftPan
{
float:right;
background-image: url(images/RH1.bmp);
background-position:right top;
border-bottom : 2px solid black;
border-left: 0px solid;
width:583px;
height:210px;
}
.Navigation
{
margin-left:3px;
margin-right:3px;
}
{
margin-bottom:10px;
margin-left:20px;
margin-right:20px;
margin-top:20px;
}
#LeftPan
{
float:right;
background-image: url(images/RH1.bmp);
background-position:right top;
border-bottom : 2px solid black;
border-left: 0px solid;
width:582px;
height:210px;
}
.Navigation
{
margin-left:3px;
margin-right:3px;
}
#sidebar1 {
float:left;
border-right:2px solid black;
width: 243px;
height:411px;
background-color:White;
}
.LeftNevigation
{
margin-top:20px;
margin-bottom:20px;
margin-left:10px;
margin-right:5px;
}
#LeftPan1
{
float:right;
background-color:White;
width:583px;
height:411px;
}
.bodyFrame
{
margin-bottom:10px;
margin-left:20px;
}
#footer
{
float: left;
background-color: #bccfb3;
width: 824px;
height: 55px;
}
#sidebar1 {
float:left;
border-right:2px solid black;
width: 242px;
height:411px;
background-color:White;
}
.LeftNevigation
{
margin-top:20px;
margin-bottom:20px;
margin-left:10px;
margin-right:5px;
}
#LeftPan1
{
float:right;
background-color:White;
width:583px;
height:411px;
}
.bodyFrame
{
margin-bottom:10px;
margin-left:20px;
}
#footer
{
float: left;
background-color: #bccfb3;
width: 825px;
height: 55px;
background-color: #bccfb3;
font-weight: bold;
}
Thanking you.
Best Regards
Shital
what is Difference Between "absolute" & "relative"
Whenever i use CSS codes in the above mentioned blog, I couldn't get the output. how is it possible the css work properly in this blog. And where should I write meta tags in the blog..
I've used Classes almost exclusively, but see ID used in many code examples - probably overused. A lot of our sites are developed for use with a Content Management System, where users can submit html rich content, and have it be part of a website (not unlike a blog). By using classes around CMS content, common tags like H1, P, A, UL, OL, entered by a user can take on the pre-set common look/feel of the particular section of the website they flow into.
Then I don't have to expect users to know the particular class or id name I've chosen when preparing their content.
.class h1 {...}
.class p {...}
For example your style sheet would define:
.announcement h1 {...}
.announcement p {...}
.article h1 {...}
.article p {...}
Then in the html:
<div class=announcement>
user announcement content here
</div>
<div class=article>
user article content here
</div>
(how you get the user content into the html depends upon your CMS implementation - so I've left that out here)
Hope this is useful to someone out there.
3 years on and this article is still coming up trumps!
Very useful and clear, thanks.
Think of 'id' as a way to divide the page into specific, physical regions (nav bar, menu, etc.). Think of classes as a way to decorate things in a way that may occur anywhere (hyperlinks, images, quotes, etc.).
hi
its realy nice explanation
Thank u
thanks for the explanation..
to Talvar also..
Much like others have mentioned, I was trying to google the difference between class and ID and found this article. It's amazing that not only is the article extremely informative, but the comments provided even further insight. I've bookmarked it for reference and thank you dearly.
Quite useful. Am gladded to see people willing to share their knowledge.
You shoud check you blog with W3
it has a xhtml error and some css stuff
regards and thanks for the tip
I usually let someone else to do the css thingy, but i have to do it on my own this time :)
so thanks for your useful info
AMAZAING .... still coming up first on google and well worth it. As long as I have been designing...... I was in the same boat. Sounds like fundamentals but when you learned CSS by teaching yourself and dissecting others sheets....this 'small' thing is quite possibly something you missed and need to know.
I have used both - but thought the only reason to use one over another was for browser compatibility issues depending on where and how it was used.
In 10 minutes of going through this entire thread I NOW completely understand what I have been doing all along and how it will truly benefit me.
I understood ...but without an exact explanation! I used Id as a wrapper or container for page structure, (e.g. Container, header, content, footer)
Then used classes for styling everything contained within those elements.
HOW DID THIS BENEFIT ME....??
I have been designing for quite some time always trying to learn the newest stuff like ajax, protopye and all the scripting libraries.
I was using ajax on a project and didn't know why I couldn't update a <div> with the external page it was calling!!
DING! LIGHTBULB - the JavaScript is looking for the ID ....not the class. BINGO!!
I was trying to update a class....switched to ID and BINGOBANGO!
This was so helpful - I would like to quote everyone all at once on this thread as there has been many good comments that have all said it very well.
THANKS A MILLION!!
Old but useful post.
thanks for this. :D
dhimes - "Think of 'id' as a way to divide the page into specific, physical regions (nav bar, menu, etc.). Think of classes as a way to decorate things in a way that may occur anywhere (hyperlinks, images, quotes, etc.)."
I had to repeat this one. dhimes has made a great visually descriptive definition. Whenever I code I have to be able to leap to the end result in my head and this clears it up for me. Good job. Good Thread. Yay, everybody...
cool stuff. handy!
I agree with girozone, dhimes has the perfect description of the differences between id and class. Somehow I got to understand it now, after googling it! Thanks for everybody's post and comments......Cheers!
First comment in 2009 :)
It helped me, too :) Thanks!
I found this article searching Google for the difference between ID and CLASS selectors. This answered my question perfectly and in a really simple to understand way. Thanks!
Many thanks guys :)
Wonderful explanation and very illustrative.
As far as coward is concerned, I choose not to dignify that comment with a response. :) As far as the difference between absolute and relative question, http://www.w3schools.com has wonderful examples of each and http://www.webtechu.com has excellent online classes that teach you what you need to know for the developer starting out, or if you just want to make your own homepages.
On my homepage, If you view the source code of my css external sheet, you see where id is important for the scripting and class for the drop down menu.
In advance, I know I used id improperly in a few places, but all that will be ammended.
I was really looking for that!
That´s very helpfull! I am teaching HTML at a social project in Colombia and students asked me that several times. I was always guessing.
Thank you!
Oops! and I thought I was the only one wondering about the difference between id and class...good to know I'm not alone, and good to learn new stuff.
Thanks!
the original article should be updated!
I learned CSS through w3 website and 3 different books and unless you were someone who learned completely from code, every CSS lesson mentions the difference between class and id. Neither those sources, nor this article, explained why I would use id at all since all the advantages of id are possible with class alone.
It was only within the first few comments to the article did the real reason emerge: IDs are used for calls in programming. I have yet to come across a single CSS lesson that mentions this important fact. Please update the article to explain this is the reason IDs should be used, not just for assigning arbitrary uniqueness to elements for the sake of a misguided ideology of good css habits
Thanks for useful info!
i m also luking for the deiff bet id and class
i must say this is very helpful to know abt that..........
i get more knowledge also..........
thanx to all
a few years back i read it... now I'm reading it again... lol, I don't use much CSS or developing sites, and thats why i keep coming back, I like to learn and this site has been a good place to start... keep up the good work...
Like many others I found this article through Google. Firstly the post was very informative but coupled with quite a few of the other comments in the style of 'Think of it this way...' it really helps with one of those basic issues. Great stuff.
Thx!
is there a rule about using div id's to structure the entire webpage? is it wrong to not use div class?
i made a webpage entirely with div id's and tested it with ie 8 ,FF,opera,safari and netscape and all is well.
thanks a lot, this is really helpful.....
I've been using both all this time and never knew the difference or why the differences are different! It's October 28, 2009 and this post is still very useful.... in addition to the comments of course.... and thanks to dhimes for the visual explanation... i have been enlightened - almost five years on!
Thanks for helping me understand the difference between class (which I have used for the last 8 years) and id which I have never used.
Just wondering if I can convert id in Suckerfish's drop down CSS menus (http://www.htmldog.com/articles/suckerfish/dropdowns/) to class.
This id vs class is something I just can't remember... Until now. Thanks for clear explanation. Especially the JavaScript GetElementById mentioned in one of the comments makes it easy to understand when I would use Id instead of class.
Like many people who posted here, I did a search on what the difference is between id and class in CSS, and this page came up. Thanks a lot for the information and discussion!
thx for your post, it made me confused when I tried to identify id and class as well, after a few change and check w3c validation then, id is used just once but class can be used many times
Wow, I am thoroughly impressed with not only the original article but the information that has been posted in the comments over the years.
Thank you all!
good to know... it was very helpful:D thanks a lot !
ThanQ
thanks info
years later and this bit of info is still VERY useful! :D
Thanks for the article
Do you know what happens if you do use multiple IDs? is it just bad form or would the page fall apart?
Ta
Rob
Thanks for the article
Do you know what happens if you do use multiple IDs? is it just bad form or would the page fall apart?
Ta
Rob
Nice Explanation.
thanks for such great information which saved lots of time confusions of freshers and new to css
Hi guys,
Can you please give a tutorial about ID & Classe in CSS i've started webdesgining i'm confuse in ID & Class please give me a guidens
Thnx
Regards
Somya
Thanks for useful info!
finally i've found out what is the difference between id and class. i was always wondering how to use them. however, i always used only "class" and "id" was something strange to me. at least now i understand that it also has a very distinct purpose
not that hard to figure out
Post Comments
If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.
Wow, that's good to know. I've been wondering myself what's the difference between "class" and "id".
thanks for sharing.
Permalink