In this post, we will demonstrate the basic difference between Id and Class in html element styled with CSS.
Let us consider the below simple example html code, where we have create two ID and two Class in CSS.
!DOCTYPE html>
<html>
<head>
<style>
#exampleId1 {
background-color: red;
font-size:20px;
}
#exampleId2 {
text-transform: uppercase;
}
.exampleClass1 {
background-color: yellow;
font-size:20px;
}
.exampleClass2 {
text-transform: uppercase;
}
</style>
</head>
<body>
<p id="exampleId1">Para1 - This paragraph is styled with id "exampleId1"</p>
<p id="exampleId1" id="exampleId">Para2 - This paragraph is styled with id "exampleId1" and "exampleId2"</p>
<p class="exampleClass1">Para3 - This paragraph is styled with class "exampleClass1"</p>
<p class="exampleClass1 exampleClass2">Para4 - This paragraph is styled with both classes "exampleClass1" and "exampleClass2"</p>
</body>
</html>
When we open this html page in browser, we will see it displayed as,
Difference 1
The declaration “Id” is started with hash “#” and declaration of “class” is started with dot “.”
In below example, example Id is declared as “#exampleId1” and example class is declared as “.exampleClass1”
#exampleId1 {
background-color: red;
font-size:20px;
}
.exampleClass1 {
background-color: yellow;
font-size:20px;
}
Only one ID can be attached with the one element, but we can attach more than one Class with one element in html.
Difference 2
Below use of “exampleId1” and “exampleId2” is invalid, as it wont show error but it will not achive the actual result as can be seen for Para2.
<p id="exampleId1 exampleId2">Para2 - This paragraph is styled with id "exampleId1" and "exampleId2"</p>
Below use of “exampleClass1” and “exampleClass2” is valid and we can see the Para4 showing the proper result of converting the paragraph text to capital with background set.
<p class="exampleClass1 exampleClass2">Para4 - This paragraph is styled with both classes "exampleClass1" and "exampleClass2"</p>
2 thoughts on “Difference between an Id and Class in HTML”