id and class
An id names exactly one element on a page and is used for links and scripts, while a class labels any number of elements that share a role or style.
Choose unique IDs or reusable classes according to the relationship you need.
Once you have elements on a page, you need ways to point at them: for a style, a script or a link. HTML gives you two naming attributes that every element can use. They look similar, but one is a name and the other is a label.
The rule
id is a name for one; class is a label for many.
id gives an element a name that must be unique on the page. No two elements may share it.
<h2 id="opening-hours">Opening hours</h2>Uses of an id:
- Links to a spot on the page:
<a href="#opening-hours">jumps here. - Connecting elements: a form
labelpoints at its input withfor="email", which must match the input'sid. - Scripts that need to find one specific element.
class labels an element as a member of a group. Any number of elements can share a class, and one element can have several classes, separated by spaces:
<article class="card">...</article>
<article class="card featured">...</article>
<article class="card">...</article>Classes are the everyday hook for CSS: style .card once and every card follows.
Naming tips: use lowercase words joined by hyphens (opening-hours, price-tag), no spaces inside a single name, and names that describe what the thing is (warning) rather than how it looks today (red-text). Looks change; roles last. Names are case-sensitive, so Card and card are different.