Class and ID Selectors
Class and ID Selectors
In the previous lesson, you saw that an Element Selector (like p { color: blue; }) styles every single paragraph on your page.
But what if you have 10 paragraphs on a page, and you want:
- 8 paragraphs to stay normal dark gray,
- 1 paragraph to have a yellow warning box, and
- 1 paragraph to have a green success message?
Element selectors cannot do this! This is where Class Selectors and ID Selectors become your best friends. 🚀
The Indian School Analogy: House Badges vs Aadhaar Cards 🏷️
To never get confused between a Class and an ID, remember this simple mental model:
+-------------------------------------------------------------------------+ | CLASS vs ID: THE SCHOOL ANALOGY | +-------------------------------------------------------------------------+ | CLASS SELECTOR (.dot) --> THE SCHOOL HOUSE BADGE | | (Red House / Shivaji House) | | • Many different students can wear the same Red House badge. | | • One student can wear multiple badges (e.g., Red House + Sports Cap). | | • Reusable across many elements on the page. | | | | ID SELECTOR (#hash) --> THE STUDENT ROLL NUMBER / AADHAAR CARD | | (Roll No: 1042 / Aadhaar ID) | | • Strictly UNIQUE to one single person in the entire school. | | • No two elements on the same webpage should ever have the same ID. | +-------------------------------------------------------------------------+
1. The Class Selector (.classname)
A Class Selector targets one or more HTML elements that share a specific class attribute.
How to Write a Class in HTML and CSS:
- 1In your HTML, add the
classattribute:
- 1In your CSS, prefix the class name with a period (dot
.):
.highlight.
In HTML, you DO NOT write a dot: class="highlight" (never class=".highlight").Reusability: The Superpower of Classes
You can apply the exact same class to completely different HTML tags!
All three elements will automatically be centered!
Multi-Class Styling (Mixing & Matching)
An HTML element can have multiple classes at the same time. Separate each class name with a simple space:
This multi-class pattern is used by top frameworks like Bootstrap and Tailwind CSS!
2. The ID Selector (#idname)
An ID Selector targets one unique HTML element on the page that has a matching id attribute.
How to Write an ID in HTML and CSS:
- 1In your HTML, add the
idattribute:
- 1In your CSS, prefix the ID name with a hash symbol (
#):
⚠️ Strict Rules for IDs:
- 1Uniqueness: An ID name can be used only once per HTML page. Having two elements with
id="submit-btn"is invalid HTML! - 2One ID per element: An element cannot have multiple IDs (unlike classes).
- 3Naming rules: ID and Class names cannot start with a number (e.g.
#1headeris invalid; use#header-1instead).
Class vs ID: Head-to-Head Comparison
| Feature | Class Selector | ID Selector |
|---|---|---|
| CSS Symbol | Period / Dot (.card) | Hash / Pound (#header) |
| HTML Attribute | class="card" | id="header" |
| How many elements can have it? | Unlimited elements on the page | Only 1 unique element on the page |
| Can one element have multiple? | Yes (class="btn btn-large btn-blue") | No (Only 1 ID per element) |
| Specificity (Priority) | Medium priority | High priority (Overrides classes) |
| Best Used For | Reusable components (cards, buttons, alerts) | Unique landmarks (header, footer, modal container) |
The Specificity Showdown (Who Wins?)
What happens if an element has both an ID and a Class rule that specify conflicting text colors?
The Winner is: ID Selector (color: red;) 🏆
Because an ID is unique to a single element, the browser considers it much more specific than a class. An ID rule will always beat a class rule, no matter what order they are written in your stylesheet!
Common Beginner Mistakes (Do's and Don'ts)
| What Beginners Do (Don't ❌) | What You Should Do Instead (Do ✅) | Why? |
|---|---|---|
<div class=".card"> | <div class="card"> | The dot (.) belongs in the CSS file, never inside the HTML attribute. |
Using the same id="nav" on 3 different menus. | Use class="nav" on all 3 menus. | IDs must be strictly unique per webpage. |
Giving an element multiple IDs: id="main top". | Use multiple classes: class="main top". | HTML only allows a single value inside id="...". |
.1st-box { ... } (Starts with a number) | .first-box or .box-1 { ... } | CSS class and ID names must not start with a digit. |
Quick Revision Summary
- A Class Selector starts with a dot (
.) in CSS and is reusable on multiple elements. - An ID Selector starts with a hash (
#) in CSS and must be unique to one element on the page. - In HTML attributes, never include the dot or hash (write
class="card", notclass=".card"). - An element can have multiple classes separated by spaces (
class="badge badge-success"). - In a specificity battle, ID rules override Class rules.
Practice Quiz
Test your understanding with these multiple-choice questions:
1. Which symbol is used in a CSS file to select an element by its class name?
A. # B. . C. * D. @ Answer: B Explanation: A period or dot (.) is used in CSS to define a class selector (e.g., .highlight { color: red; }).
2. Which of the following statements about ID selectors is completely TRUE?
A. An ID name must begin with a number B. Multiple elements on the same webpage should share the exact same ID C. An ID must be unique to only one element per webpage D. ID rules have lower priority than element selectors Answer: C Explanation: In HTML and CSS, an ID must be unique on the page. No two elements on the same document should share the same ID.
3. Which HTML snippet correctly assigns two different classes to a single button?
A. <button class="btn, btn-primary"> B. <button class="btn" class="btn-primary"> C. <button class="btn btn-primary"> D. <button class=".btn .btn-primary"> Answer: C Explanation: Multiple classes are assigned inside a single class attribute separated by a space, without any dots or commas (class="btn btn-primary").
4. In a CSS file, which selector matches the HTML tag <div id="profile-card">?
A. .profile-card B. profile-card C. #profile-card D. *profile-card Answer: C Explanation: The hash symbol (#) is used in CSS to target an element by its ID attribute (#profile-card).
5. If an element has class="text-blue" (setting blue text) and id="title" (setting red text), what color will the text display?
A. Blue B. Red C. Purple (a mix of red and blue) D. Black (Browser Default) Answer: B Explanation: ID selectors have higher CSS specificity than class selectors. Therefore, the style defined in #title (red) will override .text-blue (blue).
Practice Challenge (Try It Yourself)
- 1Open your code editor and create
school-cards.html. - 2Create 3 student profile cards with the following HTML:
- 1Open the file in your browser. Notice how:
- All three cards share the base
.cardstyling. - Each card gets its house stripe using a secondary class (
.red-house,.blue-house,.green-house). - Priya Sharma's card gets a golden border and warm yellow background thanks to its unique
#head-girlID! 🎯
Grouping and Combinator Selectors
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Universal and Element Selectors | Grouping and Combinator Selectors |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.