While the class attribute is meant to be shared across multiple elements, the id attribute is entirely the opposite. An id provides a strictly unique identifier to a single, specific HTML element on a webpage.
Think of an id like a person's Social Security Number or passport ID—no two elements on the same page are legally allowed to share it.
To assign an ID, add the id attribute to your tag. When you write CSS, you target an ID by using a hash or pound symbol (#) instead of a period.
<!-- CSS -->
<style>
#special-banner {
background-color: black;
color: gold;
text-align: center;
padding: 15px;
}
</style>
<!-- HTML -->
<!-- There should only ever be ONE 'special-banner' on this page -->
<div id="special-banner">
Grand Opening Sale - 50% Off Today Only!
</div>
Understanding when to use a class and when to use an ID is a core skill for any web developer.
| Feature | The class Attribute |
The id Attribute |
|---|---|---|
| Uniqueness | Can be used on infinite elements simultaneously. | Must be completely unique per page. |
| CSS Selector | Starts with a period (.box) |
Starts with a hash/pound (#header) |
| Primary Use Case | General aesthetic styling (fonts, colors, padding). | Layout structure, anchor linking, JavaScript targeting. |
One of the most practical uses for an ID is creating a page bookmark. If you have a very long article, you can assign an ID to a heading at the bottom of the page, and create a link at the top that instantly jumps the user down to that exact heading.
<!-- 1. The Link (Note the '#' symbol in the href) -->
<a href="#chapter4">Jump directly to Chapter 4</a>
... lots of page content ...
<!-- 2. The Target Destination -->
<h2 id="chapter4">Chapter 4: The Conclusion</h2>
Because an ID is guaranteed to be unique, it is the safest, fastest, and most common way for JavaScript to reach into the HTML document and grab one specific element to interact with.
<!-- The HTML Tag -->
<p id="demo">Original Text</p>
<!-- The JavaScript Code -->
<script>
// This instantly finds the element above and changes its text
document.getElementById("demo").innerHTML = "Text changed by JavaScript!";
</script>