HTML: Classes vs IDs

Codecademy Team
In this article, learn more about the differences between HTML classes and IDs.

Classes vs. IDs

Requirements:

  1. Classes
  2. IDs

Classes

Classes are used to denote multiple elements that will receive the same styling. For example, assume that we’re creating a table that displays a list of students in a classroom. If we wanted each row representing a student to have certain CSS applied to it, we could write:

<!DOCTYPE html>
<html>
<head>
<title>My Classroom</title>
</head>
<body>
<table>
<tr class=”student-row”>John Smith</tr>
<tr class=”student-row”>Ken Brown</tr>
</table>
</body>
</html>

Then, to apply the CSS, we write the following in our CSS file, using the . as the CSS selector for classes:

.student-row: {
color: red;
}

This will select all elements with the class student-row and change the color of the contents to red. You can think of classes as types of elements: they’re used when you have multiple elements that you want to have the same styling.

IDs

In contrast to classes, IDs are unique and can only apply to at most one element on the page. For instance, using our table above, we can give our table element an ID:

<!DOCTYPE html>
<html>
<head>
<title>My Classroom</title>
</head>
<body>
<table>
<tr class=”student-row” id=”student-john-smith”>John Smith</tr>
<tr class=”student-row”>Alicia Rose</tr>
</table>
</body>
</html>

Now, we write the following in our CSS file, using the # as the CSS selector for IDs:

#student-john-smith: {
border: 1px solid black;
}

This will apply a black border to the row containing “John Smith”. Use IDs when you have a single element that you want to apply styling to, but would be difficult to select otherwise with CSS. Now, you can easily give elements IDs in order to fully style and customize your page!