HTML: Classes vs IDs
Classes vs. IDs
Requirements:
- Completed Codecademy Learn HTML & CSS Unit 5 Lesson 1
- Classes
- 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!
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
HTML Glossary
Programming reference for HTML elements. - Article
CSS Glossary
Programming reference for CSS covering Comments, Properties, and Selectors - Article
What are the Utility Classes in Tailwind CSS?
Learn about Tailwind CSS utility classes, their importance, and usage through a real-world example.
Learn more on Codecademy
- Free course
Learn CSS
In this CSS tutorial, you’ll learn how to add CSS to visually transform HTML into eye-catching sites.Beginner Friendly6 hours - Skill path
Build a Website with HTML, CSS, and GitHub Pages
Learn the basics of web development to build your own website.Includes 9 CoursesWith CertificateBeginner Friendly14 hours - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly7 hours