Classes vs. IDs
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:
<tr class=”student-row”>John Smith</tr>
<tr class=”student-row”>Ken Brown</tr>
Then, to apply the CSS, we write the following in our CSS file, using the
. as the CSS selector for classes:
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.
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:
<tr class=”student-row” id=”student-john-smith”>John Smith</tr>
<tr class=”student-row”>Alicia Rose</tr>
Now, we write the following in our CSS file, using the
# as the CSS selector for IDs:
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!