ComparisonComparisons

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.

On this page

Side-by-side comparison

#
  • Uniqueness

    class
    Can repeat across many elements
    id
    Must be unique across the whole document
  • Number of values per element

    class
    Many, separated by spaces
    id
    A single value
  • Specificity in CSS

    class
    Low, easy to override
    id
    Very high, hard to override
  • Typical uses

    class
    Styling many elements, classList in JS
    id
    Anchors, label for, getElementById
  • Recommendation for styling

    class
    Yes, the basic approach in CSS
    id
    Better to avoid, due to its high specificity

Example

#
HTML
<p class="card">First card</p>
<p class="card">Second card, also with the class card</p>
<h2 id="pricing">Pricing</h2>
Preview

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

#
Syntax
<element class="name second-name">
<element id="unique-name">

More examples

#
id links a label to a field
HTML
<label for="email">E-mail</label>
<input id="email" type="email">
Preview
A duplicate id is a bug
HTML
<button id="save" type="button">Save</button>
<button id="save" type="button">Save (duplicate id!)</button>
Preview

getElementById will only return the first one. A class can be repeated without any problem.

Good practices

#
  • Reach for class when styling in CSS. An #id selector has very high specificity and is hard to override.
  • id must 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

#

Spotted a mistake or missing an example? Write to us.