23. class vs id
Defining the identity of elements for CSS and JavaScript
Real-life analogy
Class is like a 'school uniform' that many students can wear at the same time, while ID is like a student's 'Aadhaar card number' or roll number, which can belong to only one person in the entire school!
Explanation
1. The class attribute (class):
- You can give the same class name to many different elements on the page.
- In CSS it is selected with a dot
.classname. - An element can have more than one class (e.g.
class="btn btn-primary").
2. The id attribute (id):
- On an entire HTML page, an ID name can be given to one and only one element (Unique).
- In CSS it is selected with a hash
#idname. - It is essential for
document.getElementById()in JavaScript.
Golden rules
- An ID name must not start with a number (Number).
- Never give two different tags the same ID within one page.
Common mistake
Writing the same id="header" three times on one page. This makes the JavaScript code stop working.
Example code
<!DOCTYPE html>
<html>
<head>
<style>
.card { background: #f8fafc; border: 1px solid #cbd5e1; padding: 10px; border-radius: 6px; margin-bottom: 8px; }
.highlight { border-color: #10b981; background: #ecfdf5; font-weight: bold; }
#special-box { background: #eff6ff; border: 2px solid #3b82f6; }
</style>
</head>
<body style="font-family: sans-serif; padding: 20px;">
<div class="card">Card 1 (plain class)</div>
<div class="card highlight">Card 2 (two classes together)</div>
<div class="card" id="special-box">Card 3 (this one has a unique ID)</div>
</body>
</html>
Quick quiz
Which symbol is placed before the name to style a 'Class' in CSS?
- Hash (#)
- Dot (.)
- At (@)
- Slash (/)
Show answer
Answer: Dot (.)
In CSS, a class is preceded by a dot (.) and an ID by a hash (#).