Tutorial: CSS. ID vs Class
Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, spacing) to Web documents. There is often confusion about when it is appropriate to use CSS IDs and when CSS Classes should be used instead. This lesson is geared to display the differences, as well as provide more information about CSS IDs.
What is an ID selector?
The W3C defines class ID as “a unique identifier to an element”. But what does that actually mean? Hopefully you have already learned CSS, if not, I recommend that you do so.
CSS IDs are similar to classes in that they define a special case for an element. Below is an example of a CSS ID.
CSS CODE:
<style>#exampleID1 { background-color: white; }
#exampleID2 { text-transform: uppercase; } </style>
HTML CODE:
<div id="ExampleID1">This paragraph has an ID name of "exampleID1" and has a white CSS defined background</p><div id=”ExampleID2″>This paragraph has an ID name of “exampleID2″ and has had its text transformed to uppercase letters.
Notice that an ID’s CSS is an HTML element, followed by a “#”, and finally ID’s name. The end result looks something like “element#idname”. Also, be sure to absorb the fact that when an ID is used in HTML, we must use “id=name” instead of “class=name” to reference it!
The symbol for an ID is the # symbol. For a class, it is a . (period) symbol. Here is an example:
CSS CODE:
<style>.class1 { background-color: white; }
.class2 { text-transform: uppercase; } </style>
HTML CODE:
<div class="class1">This paragraph has an CLASS name of "class1" and has a white CSS defined background</p><div class=”class2″>This paragraph has an CLASS name of “class2″ and has had its text transformed to uppercase letters.
Think of a ID being one person and the CLASS being a group of people. Read on to understand this.
When should I use a ID or Class?
It is very common that an ID element only should occur once within your page or document. From my experience, this makes sense because there are usually only one menu per page, one banner, and usually only one content pane. That is why an ID is used. This is where CLASS gets to be important. You would use the CLASS element when you want the same look on different pages. Instead of typing out a few ID elements, all you need to do is type out a CLASS element and apply the <div class=”element”>INFO</div> to each page where you want them to look the same.









yeah sooooooooooooooooooo - alright bye!
Please leave your comment!