class vs id
class 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.
Side-by-side comparison
#| Aspect | class | id |
|---|---|---|
| Uniqueness | Can repeat across many elements | Must be unique across the whole document |
| Number of values per element | Many, separated by spaces | A single value |
| Specificity in CSS | Low, easy to override | Very high, hard to override |
| Typical uses | Styling many elements, classList in JS | Anchors, label for, getElementById |
| Recommendation for styling | Yes, the basic approach in CSS | Better to avoid, due to its high specificity |
Example
#<p class="card">First card</p>
<p class="card">Second card, also with the class card</p>
<h2 id="pricing">Pricing</h2>Definition and usage
#The class attribute can repeat: the same name can appear on many elements, and a single element can have several classes separated by spaces, e.g. class="btn btn-primary". It’s the basic way to style things in CSS and to manage elements through classList in JavaScript, and its specificity is low and easy to override.
The id attribute must be unique across the whole document, so a single element always has only one value for it. It’s used for specific, one-off connections: an anchor in the URL (#faq), linking a <label for> to a field, or quickly finding an element with getElementById. In CSS it has very high specificity, which makes an #id selector hard to override later.
The simple rule of thumb: use class for styling many similar elements and for working with scripts. Use id for unique hooks that point to something specific (a label, an anchor, a one-off reference in JavaScript).
Syntax
#<element class="name second-name">
<element id="unique-name">More examples
#<label for="email">E-mail</label>
<input id="email" type="email"><button id="save" type="button">Save</button>
<button id="save" type="button">Save (duplicate id!)</button>getElementById will only return the first one. A class can be repeated without any problem.
Good practices
#- Reach for
classwhen styling in CSS. An#idselector has very high specificity and is hard to override. idmust be unique across the whole document, not just within a single component.- A single element can have many classes separated by spaces, but only one
id.
Related entries
#- classA list of class names that CSS and JavaScript use to find an element.
- idA unique identifier for an element across the whole document.
- <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.
- data-*Custom attributes for storing data for scripts and styles.
Spotted a mistake or missing an example? Write to us.