CSS ID and Class – What’s the Difference?
CSS IDs (#id
) and Classes (.class
) are used to apply styles to HTML elements. Here’s how they work:
1. CSS ID (#id
)
- Used to target a single, unique element.
- Denoted by a
#
before the name. - Each ID must be unique on a page.
Example
✅ Only one element can have id="special-text"
on a page.
2. CSS Class (.class
)
- Used to target multiple elements.
- Denoted by a
.
before the name. - It can be applied to many elements.
Example
✅ Multiple elements can have class="highlight"
.
3. Difference Between ID and Class
Feature | ID (#id ) | Class (.class ) |
---|---|---|
Usage | Unique for one element | Can be used on multiple elements |
Selector | #id | .class |
Specificity | Higher specificity | Lower specificity |
Best Practice | Used for unique elements (e.g., #header ) | Used for reusable styles (e.g., .button ) |
4. Using ID and Class Together
You can combine IDs and Classes for better styling.
Example
✅ #main-text
applies red color, and .highlight
applies font size.
5. Multiple Classes in One Element
✅ The text will be bold and italic.
6. Nested Selectors (Class inside ID)
✅ Only .title
inside #container
will be green.
Which One Should You Use?
✔ Use class
for reusable styles.
✔ Use id
for unique elements like navigation or forms.
✔ Avoid using IDs for styling unless necessary (better for JavaScript targeting).