CSS IDs: The Unique Identifiers
While classes bring modularity and reuse to your styles, IDs bring precision. They are the single source of truth for an element, acting as styling hooks, navigation anchors, and direct pipelines to JavaScript logic.
The Golden Rule: Uniqueness
The most important rule when using the id attribute in HTML is that it must be absolutely unique within a document. You cannot have two elements on the same webpage with id="header".
In CSS, you target this unique element using the hash or pound symbol (#). Because the browser knows only one element exists with this ID, it can locate and style it incredibly fast.
Specificity Showdown
CSS applies rules based on a weight system known as Specificity. If two rules clash, the heavier rule wins.
An ID selector carries significantly more weight than a class selector. If an element has class="btn-red" but also id="btn-green", and both apply a background color, the ID's style will overwhelmingly defeat the class's style.
Beyond Styling: Anchors & JS
- Fragment Links (Anchors): If you assign an ID to a section (e.g.,
id="contact"), you can link directly to it from anywhere using an anchor tag:<a href="#contact">. Clicking this link scrolls the browser directly to that element. - JavaScript Targeting: IDs are heavily used in JS via
document.getElementById('my-id'). It is the most performant way to select a single DOM node.
Best Practices tip+
Limit IDs in CSS. Because of their massive specificity weight, heavily styling with IDs makes your CSS rigid and hard to override later. It is widely considered best practice to use Classes (.class) for styling, and reserve IDs for JavaScript hooks and page anchors.
❓ Frequently Asked Questions
What happens if I use the same ID twice?
It invalidates your HTML document. While CSS *might* still apply the styles to both elements in modern browsers, JavaScript will fail (getElementById will only return the first occurrence), and fragment links will behave unpredictably.
How do I override an ID in CSS?
It is very difficult. You either have to use another ID with a class chained to it (e.g., #my-id.override), use an inline style in the HTML, or use the dreaded !important flag. This is why styling with classes is preferred!
