id and class
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.
The shortcut
Ask "Could there ever be two of these on this page?" If never, id is allowed. If there could be, use a class.
The comments section
There is only one per page, and links jump to it:
id="comments".
The trap is reusing an id for several elements because it "works" in CSS. Links, labels and scripts expect one match, and duplicates break them in confusing ways.
Both attributes are global: every HTML element accepts them, from p to img to li. That also means you do not need to wrap something in an extra div just to give it a class. Put the class straight on the element that needs it.
Drills
Answer fast — trust the rule.
How many elements on one page may share id="menu"?
How do you give an element two classes, btn and large?
Which name follows good practice for a class on warning messages?
A form's <label for="phone"> should connect to its input. What must the input have?
Remember
idnames one unique element;classlabels any number, and one element can have many classes.- Shortcut: "could there ever be two?" Yes means
class. - Trap: duplicate ids, and class names that describe looks instead of roles.
