Home / Learn HTML / HTML Classes and IDs

HTML Classes and IDs

Classes and ids are names. CSS and JavaScript use the names to find your elements.

Definition

class and id are attributes that give names to elements so CSS and JavaScript can find them.

classid
Unique?No, many elements can share a classYes, only one element per page
Many per element?Yes, separate with spacesNo, only one
CSS selector.name#name
Link targetNoYes: href="#name"

Choose names that describe the purpose (price, card) not the look (red-big). Names are case sensitive and must not contain spaces.

Theory in plain words

class vs idclassMany elementsSelector .nameidOne elementSelector #name
class vs id

What it is

class and id are attributes that name elements so CSS and JavaScript can find them.

Why we use it

Without names you could not style one card differently from another.

How it works

A class can be used on many elements and one element can have several. An id must be unique on the page.

Where it is used

  • .card, .button style groups
  • #header, #main for one-off elements
  • Anchor links to #section
Class: reuse a styleTry it Yourself
Several classes on one elementTry it Yourself
Id: one special elementTry it Yourself
Select by class in JavaScriptTry it Yourself
Select by id in JavaScriptTry it Yourself
Jump to an idTry it Yourself
Class on different tagsTry it Yourself
Tag and class togetherTry it Yourself
classid
Unique?No, reuse freelyYes, once per page
CSS.name#name
Per elementMany classesOne id
Use forStyling groupsLinks and one off items
Toggle a class with a buttonTry it Yourself
Class and id in CSS togetherTry it Yourself

Quick quiz

1. CSS selects a class with

2. CSS selects an id with

3. Can many elements share a class?

My notes
Ask a question about this lesson