ID vs Class in CSS Web Design

Share |

For anybody who has spent any time working with CSS (cascading style sheets), you have to know there is a lot of confusion when it comes to using an id or a class when compiling your web site layout.  Both are selectors, but how should they be used?

What is the ID selector?

The general syntax for an ID selector is:

#idselector {property:value;}

This should really only be used once per web page.  For example if I was designing a standard site with the body of the page on one side and the sidebar on the other side, I would use two different ID selectors, one for the body and one for the sidebar.  I wouldn’t use the body one twice, because it already covers everything it needs to cover (as far as styling goes) the first time I used it.  You can use it to cover a lot of things in one clean sweep, all at once.

What is the Class selector?

The general syntax for a Class selector is:

.classselector {property:value;}

The Class selector is to be used for defining smaller elements within the ID selector.  Going back to my earlier example, lets say I wanted to define how my headline tags looked – and my links for that section of the web page.  I would then turn around and use a Class selector for each of those.  Think of this as the “picky” selector, allowing you to tweak things within the ID selector.

In a nutshell, you should use the ID selector when there is only one occurrence per web page, and the Class selector when there are more than one occurrence per web page.  What happens if you do it the “wrong way”, well nothing really – of course learning how to use your web design tools the right way, rather than just to hack it all together, will help with troubleshooting error sand problems down the road.

Bonus: Check out the 60+ CSS Web Design Resources we collected on blog.lunarpages.com!

2 Responses to “ID vs Class in CSS Web Design”

  1. Lunartics Ryuku Says:

    I always wondered why or when I should use one rather than the other. This does a good job at explaining that in-depth, thanks for the awesome tutorial.

  2. Lunartics Jaime Soo See Says:

    Great job! Explains the usage between the two perfectly.

More Web Hosting Help