chevron_left
358 points
19 13 11

To style different elements in HTML using CSS, we use selectors. Selectors are used to identifying the element to which we want to apply a certain style. There are 4 types of basic selectors:

  • Element Selectors  → Name of the element. For example, body, h1, p, a, etc.
  • Class Selector → A name given to a particular element. 
  • ID Selector → Also a name given to a particular element.
  • Universal Selector → It applies styling to the entire webpage. It is denoted by an asterisk (*).

In this article, we are going to see the difference between the Class and ID in CSS.

Difference between Class and ID:

By Definition:

Apparently, there is not much difference between a Class and an ID, except that a class can be used with multiple elements and an ID should be used with a single element. In simple words, the ID of different elements must be unique. 

By Syntax:

A class and an ID is assigned to an HTML element using the same syntax which is as follows:

<element class = "name"></element>
<element id = "name"></element>

but in the CSS file, we use dot(.) for the class and hash (#) for the id. The syntax is as follows:

.class_name{
    property:value;
}

#id_name{
    property:value;
}

These are some differences between the class and ID in CSS. Now, let’s see the class and id in action:

Class Example:

HTML:

<!DOCTYPE HTML>
<html>

<head>

<title>Class Example</title>
<link href = "stylesheet.css" type="css/text" rel="stylesheet" />

</head>

<body>

<h1 class = "HEADING">This is a heading whose class is "HEADING"</h1>

</body>
</html>

CSS:

.HEADING{
	background-color:#FF3366;
	color: #FFCC33;
	border: 2px solid #00CC99;
	width: 50%;
}

 

Output:

ID Example:

HTML:

<!DOCTYPE HTML>

<head>
<title>ID Example</title>
<link href = "stylesheet.css" type="text/css" rel="stylesheet" />
</head>

<body>
<p id = "PARAGRAPH">This is a paragraph with "PARAGRAPH" ID</p>
</body>
</html>

CSS:

#PARAGRAPH{
	background-color:#FF3366;
	color: #FFCC33;
	border: 2px solid #00CC99;
	width: 50%;
}

Output:

1 Comment

Good post about class and ids in css. Great job. Continue to post. Thank you so much.

More Posts

What is the difference between id and class in css Sanjana Sagar - May 22
Difference between class and id attribute in html Sanjana Sagar - May 28
What is the difference between absolute and relative positioning? Hafsa_Rao - Jul 18
Sidebar menu hover hide/show CSS kunal verma - Nov 7, 2020
What is the difference between Class and ID in html ? Tushar Shuvro - May 1, 2020
What is the difference between a class and an interface mhfaisal - Jun 12
What is the difference between class and structure Hafsa_Rao - Mar 19
What is the difference between margin and padding amna - Mar 17
Difference between visibility hidden and display none Hafsa_Rao - Jul 9
What is the difference between html elements and tags? amna - Mar 17