HTML/ CSS: Use id or class?

January 20, 2022

HTML/ CSS: Use id or class?

In this article we will answer the question: use id or class? In your web projects, to have concise and easy-to-maintain codes.

use id or class cover

Hey you programmer, ok? Let’s learn something new!

Ids and classes are attributes of HTML, and are primarily used to select elements for both styling and JavaScript events.

Let’s see the differences between both attributes:

Id: One per page, identified in CSS as ‘#’;

Classes: Can be used multiple times on the page, identified in CSS as ‘.’;

So taking advantage of the differences definition is how we will know when to use id or class

For example: we have a unique section of our slider site, so we can use an id of #slider in this element

In another case, we have a list (ul) with several items, so each item can receive the same class and so we will use it correctly

And yet in CSS, we will take advantage of the multiple times repeated class property to style the list items

Check it out this example:

<div id="slider">
 <img src="image.jpg">

 <li class="item">Item 1</li>
 <li class="item">Item 2</li>
 <li class="item">Item 3</li>
 <li class="item">Item 4</li>
 <li class="item">Item 5</li>

Basically this is the major difference, if we absorb this concept of uniqueness for id and repetition for class, we won’t have any more problems

And the problem is that HTML doesn’t give an error that stops the application if we repeat an id, this is good and bad, because on the one hand the application doesn’t stop

But on the other hand, we have an incorrect action taken by us and this can lead to consequences such as: bad code interpretation by Google


The big difference between id and class is: id we cannot repeat, class we repeat at will

So we must observe the uniqueness of an element per page, when using an id

As for classes, we will use its function, which is to reuse the style in several elements

Do you wanna learn more about HTML and CSS? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x