CSS Tutorials

adplus-dvertising
CSS ID and Class
Previous Home Next

CSS ID

ID is specified by including a number sign (#) before the selector name.In HTML, every element on your web page can be assigned a unique id attribute. This can be any text you like, but it has to be unique.

ID's are unique

  • Each element can have only one ID
  • Each page can have only one element with that ID

When I was first learning this stuff, I heard over and over that you should only use ID's once, but you can use classes over and over. It basically went in one ear and out the other because it sounded more like a good "rule of thumb" to me rather than something extremely important.

Here is one: your code will not pass validation if you use the same ID on more than one element. Validation should be important to all of us, so that alone is a big one. We'll go over more reasons for uniqueness as we go on.

Code

#title {
background-color:#FFCCFF;
color:#0000CC;
}

CSS Class

Class is specified by including a period (.) before the selector name.A class can be used several times, while an ID can only be used once, so you should use classes for items that you know you're going to use a lot.

Classes are NOT unique

  • You can use the same class on multiple elements.
  • You can use multiple classes on the same element.

Any styling information that needs to be applied to multiple objects on a page should be done with a class.

Code

p.exmle {
background:#CC99FF;
color:#990033;
} 
Simple example of ID and Class
<html>
<head>
<style>
#title {
background-color:#FFCCFF;
color:#0000CC;
}
p.exmle {
background-color:#3399FF;
color:#990033;
} 
</style>
</head>
<body>
<p id="title">It is used to show the CSS ID</p> 
<p class="exmle">It is used to show the CSS class1</p> 
<p class="exmle">It is used to show the CSS class2</p> 
</body>
</html>

Output

Previous Home Next