id and class
This is a topic on id and class within the Programmers Corner forums, part of the Technology category; Hello everyone,
I am new to CSS. I was going through many references but none of them made me understand ...
2Likes
-
1
Post By ander
-
1
Post By ander
-
Tech2 Members
id and class
Hello everyone,
I am new to CSS. I was going through many references but none of them made me understand the difference between id and class. I saw many css files but couldn't figure when they are used and when they must be avoided. Could you please explain me in detail?
Cheers
-
Tech2 Members
Re: id and class
ID = unique ID. You can only use it for one element and no more.
class = generic identifier for a class of elements
If you have a forum page for example, you would give the header section, the footer section, the login form etc. an id attribute - #header, #footer, #loginForm. You would give each post in the page, each profile picture displayed, etc. a class attribute - .post, .profilePic, etc. There would only be one header section and footer section in a page, but you can have dozens of posts and profile pictures.
I'm back, baby! =P

-
Tech2 Members
Re: id and class
So you mean class is used for something that is repeated but id is for something that is used for only those which do not appear more than once in a page. So if I have a header, I can use #header only once in the stylesheet with it's needed properties?
I have one more doubt, if id has limitations why can't we just use class and get away?
Last edited by ankur218; 07-17-2012 at 06:32 PM.
-
Tech2 Members
Re: id and class
There are many reasons -
- Semantics - an id attribute immediately makes it clear that you're referring to one element. It might not seem like much, but it's really useful if you need to work with someone else's code or look at your own code after a long time
- CSS specificity - like you mention in your other question, an id attribute has much higher specificity than a class name. This is so important that most people take it for granted.
- Scripting - using an id attribute appropriately would make your JS code faster (although the difference is admittedly very small in modern browsers), and cleaner, because you expect to get only one element when you ask the browser for #something.
- Linking - you can directly link to any element with an id attribute to make the browser scroll the page so that that element is at the top. Make a long HTML page and give the first element in the page an id attribute of "top". Then make a link at the bottom of the page to your_page.html#top. Clicking that link should immediately scroll the page up. Very useful stuff.
Oh and you can use class names and ids at the same time on the same element.
I'm back, baby! =P

Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules