HTML Tutorial · Page Structure · Lesson 12 of 34

HTML Classes and IDs

Name elements with class and id for styling, scripting and linking.

class

class assigns one or more names (separated by spaces) to an element. Many elements can share a class — it's the main hook for CSS:

Example 1Try it yourself
<style>
  .card { border: 1px solid #cbd5e1; border-radius: 8px; padding: 8px 12px; margin: 6px 0; font-family: sans-serif; }
  .card.featured { border-color: #2563eb; background: #eff6ff; }
  #special-offer { font-weight: bold; color: #b91c1c; }
</style>
<div class="card">A regular card</div>
<div class="card featured">A featured card (two classes)</div>
<p id="special-offer" data-discount="20">This element has a unique id.</p>

id

id must be unique on the page. Use it for fragment links (#pricing), connecting labels to inputs, and JavaScript lookups. For styling, prefer classes.

data-* attributes

Custom data-* attributes store extra information for scripts: <button data-product-id="42">, read in JavaScript as button.dataset.productId.

Test yourself

Can two elements on the same page share an id?

  1. Yes
  2. No — ids must be unique
Show answer

Answer: No — ids must be unique