id
A unique identifier for an element across the whole document.
- Applies to
- All HTML elements
Example
#<nav>
<a href="#pricing">Go to pricing</a>
</nav>
<label for="email">Email</label>
<input id="email" type="email" placeholder="you@example.com">
<h2 id="pricing">Pricing</h2>
<p>Clicking the “Email” label moves the cursor into the field.</p>Definition and usage
#The id attribute gives an element a name that must be unique on the whole page. With it you can link to a specific spot (href="#contact"), connect a label to a form field (<label for="email">), or quickly find an element in JavaScript.
The value must not contain spaces and should not be empty. Formally it may start with a digit, but in CSS selectors such an identifier has to be escaped, so it is better to start with a letter.
For styling, classes are more convenient. The #id selector has very high specificity, which makes it hard to override later.
Syntax
#<element id="unique-name">…</element>Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- A repeated
idis a bug.getElementByIdreturns only the first element, and labels and anchors may point to the wrong place. - Use descriptive, hyphenated names, for example
contact-form.
Related entries
#- class vs idclass can repeat across many elements and combine several at once. id must be unique across the whole document and is used for anchors, labels and JS.
- classA list of class names that CSS and JavaScript use to find an element.
- <label>A form field’s label. Clicking the label moves the cursor to the field.
- <a>A link to another page, a file, an email address, or a place on the same page.
- tabindexDecides whether an element can be focused with the Tab key and in what order.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.