CSS Class vs ID

When I first learned CSS, the biggest challenge for me was learning the difference between “ID” and “CLASS” selectors. I struggled with the concept until I learned that “ID” selectors are unique and can only be used once in a page layout. On the other hand, “CLASS” selectors can occur multiple times in a single page layout. A good example of using the “CLASS” selector is using it for posts or articles which can occur many times in a single page. See some examples below.

ID Selectors

ID selectors are unique. They occur only once in a page layout. A good use for an ID selector are headers, footers, menus, sidebars, etc. Remember, it’s must be unique and can NOT be repeated in a page.

Apply CSS to ID selectors by using the # pound sign. I associate “ID” selectors to an ID Card or a Drivers License which contains a unique number. Therefore IDs have unique numbers and uses the # pound sign.

CLASS selectors

CLASS selectors on the other hand, occur multiple times in a page such as divs for posts, articles, etc.

Apply CSS to CLASS selectors by using the . period sign. I associate CLASS selectors to a “class period” like in a school enviroment — a class period. The CSS code under .post in this case will apply to every instance of the CLASS selector.

I hope this short article clears up some of the confusion between ID and CLASSES for first time CSS coders. I hope it gives you a much clearer picture as to which selectors to use when designing your next page layout.

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4.33 out of 5)
Loading ... Loading ...

4 Responses to “CSS Class vs ID”

  1. Good intro. If you feel like following up, you may want to mention things like tag selectors, child selectors and pseudo-classes as well, as they’re definitely as useful (sometimes even more useful) than id or class based selectors.

    I know that’s not exactly the scope of this post, but just a suggestion :) Again, good intro though.

  2. Matthew. Thanks for leaving a comment. I’ve thought about a follow-up article along the same lines you mentioned. Stay tuned.

  3. thanks for this useful article !

  4. thanks good advice..mind about others that are just important
    like header footer and template widgets

Leave a Reply