The Difference Between ID and Class

Mandeep Kaur
3 min readMay 8, 2020

--

© Mandeep Kaur

When writing CSS, class and ID selectors are used to identify various HTML elements. The main benefit of setting class or ID is that we can present the same HTML element differently, depending on its class or ID.

ID’s are unique

An ID is a unique identifier of the HTML element to which a particular style must be applied. It is used only when a single HTML element on the web page must have a specific style. The # symbol and the id of the HTML element name are used to select the desired element.

How to add an ID to our HTML element: <div id= “id”>

How to use them in our CSS: To add style to an element with an id, we preface the id with a # symbol in our CSS.

Syntax: #blue { color: #015cf8; font-size: bold; }

Example

In this example, we assigned blue as id selector for the third paragraph (id=“blue”), and declared its style using color property — #blue {color: #015cf8;} in the <head> section. It means that the HTML element having id selector blue will be displayed in #015cf8.

Classes are not unique

A class selector is used when the same style must be applied to multiple HTML elements on the same web page. The . symbol, along with the class name, is used to select the desired class.

How to add a class to our HTML element: <div class=“class”>

HTML element can have multiple classes: <div class=“class another-class”>

How to use them in our CSS: To add style to all elements that are part of a particular class, we preface the class name with a period (.) in our CSS.

Syntax: .blue { color: #015cf8; font-size: bold; }

Example

In this example, we assigned blue as class selector for the header and the third paragraph (class=“blue”), and declared its style using color property — .blue {color: #015cf8;} in the <head> section. It means that the HTML elements having class selector blue will be displayed in #015cf8.

Conclusion

The difference between an ID and a class is that the first one is unique, and the second one is not. This means that each element can have only one ID, and each page can have only one element with that ID. When using the same ID on multiple elements, the code won’t pass validation. But as the classes are not unique, the same class can be used on multiple elements, and vice versa, we can use several classes on the same element.

Thank you for reading.

--

--