HTML Class and Id attributes

The class and id attributes are used to style the HTML elements using CSS properties. But there are few differences between these two attributes.

Their differences:

1. class attribute is used to style an HTML element or group of HTML elements while id attribute is used only to identify or style one unique element in a page.
OR
For class attribute, two different HTML elements having same class name can have different CSS properties, while it is not in the case of id attribute.

Full code example

<!DOCTYPE html>
<html>
<head>

<style>

h3.className {
 text-align: center;
}

p.className {
 color: red;
}

#idName {
 color: green;
}

</style>

<meta charset="UTF-8">
<title> class and id attributes </title>
</head>

<body>

<h3 class="className"> HTML </h3>

<p class="className">
HTML is the most common language of the internet's world wide web.
</p>

<h3 id="idName"> HTML </h3>

<p id="idName">
HTML is the most common language of the internet's world wide web.
</p>

</body>
</html>
Run The code »

Output on the browser

HTML

HTML is the most common language of the internet's world wide web.

HTML

HTML is the most common language of the internet's world wide web.

If two HTML elements have same id value, we can't style them separately unlike in the case of class attribute.
In the above example, <h3> and <p> have same id (idName), the following example is wrong.

h3#idName {
 text-align: center;
}

p#idName {
 color: red;
}

The following example is true. All the styles will be applied to the HTML elements have id value__idName

#idName {
 text-align: center;
 text-decoration: underline;
}

2. Dot symbol (.) is used before the class name to define it (example:- .className) while Asterisk symbol (#) is used before the id name to define it. (example:- #idName).

Full code example

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>

.className {
 color: red;
}

#idName {
 color: green;
}

</style>

<title> class and id attributes </title>
</head>

<body>

<h3 class="className"> HTML </h3>

<p id="idName">
HTML is the most common language of the internet's world wide web.
</p>

</body>
</html>
Run The code »

Output on the browser

HTML

HTML is the most common language of the internet's world wide web.

3. For class attribute, name of the HTML element may either contain or not. i.e. you can write as .className or h3.className, both are true while in id attribute, name of the HTML element can not be contained. i.e. you can write as #idName but cannot as h3.idName.