ID vs Class

One common question when working with XHTML and CSS is whether to use the id or class attribute on an element. There are several rules that you should consider when using either attribute.

  1. Will the selector be used more than once within a document?
  2. Do the selectors need to be combined?
  3. Does the specificity matter?

If the answer to question number one or two is yes, then you need to use a class. Classes can be used more than once in a document whereas id’s cannot. A neat little CSS trick is that you can combine classes, for example:

CSS is the best!

Lastly, id’s have a higher specificity than classes, which means that the styles for the id element will be given priority over the styles for a class.

You can also use both a class and id on a single element in order to gain greater control over the element.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s