An ID is a name for one single element on a page. You set it with the id attribute and select it in CSS with a hash #.
<style>
#main-title {
color: #d94a00;
letter-spacing: 1px;
}
</style>
<h1 id="main-title">Welcome to Juniper Books</h1>
<h1>This heading has no ID</h1>
Rules for IDs
- An ID must be unique. Two elements with
id="main-title"on the same page is an error in HTML. - IDs are case sensitive and cannot contain spaces.
- An element can have an ID and classes at the same time.
ID or class?
| Class | ID | |
|---|---|---|
| Selector | .name | #name |
| Use on many elements | Yes | No, one only |
| Strength in CSS | Normal | Much stronger |
IDs are very strong in the cascade, which is exactly why many developers avoid them for styling. A rule like #sidebar a is hard to override later without writing an even stronger rule. Classes are easier to reuse and easier to change.
IDs are still useful, just not mostly for CSS. They are the target of in-page links (<a href="#contact"> jumps to id="contact"), form labels and JavaScript.