HTML class Attribute

HTML class Attribute
In HTML class Attribute is used to group elements so they can be styled with CSS or manipulated with JavaScript.
It is one of the most important attributes in HTML.
1. What Is the class Attribute?
Used to assign one or more class names to an element
Same class can be used on multiple elements
Mostly used with CSS and JavaScript
<p class="text">Hello World</p>
2. Basic Example
HTML
1 2 | <p class="highlight">This is paragraph 1</p> <p class="highlight">This is paragraph 2</p> |
CSS
CSS
1 2 3 4 | .highlight { color: red; font-weight: bold; } |
- Both paragraphs get the same style
- One class → many elements
3. Using class with <div>
1 2 3 4 5 6 7 8 9 10 11 | <div class="box">Box 1</div> <div class="box">Box 2</div> .box { width: 100px; padding: 10px; background-color: lightblue; margin: 5px; } |
4. Multiple Classes on One Element
You can apply more than one class to a single element.
1 2 3 4 5 6 7 | <p class="text large red">Hello HTML</p> .text { font-family: Arial; } .large { font-size: 20px; } .red { color: red; } |
- Classes are separated by space
- All styles are applied together
5. class Selector in CSS
CSS uses dot (.) for class selectors.
1 2 3 4 5 6 7 8 | .button { background: green; color: white; } <button class="button">Click Me</button> |
6. class vs id (Very Important)
| Feature | class | id |
|---|---|---|
| Unique | No | Yes |
| Reusable | Yes | No |
| CSS selector | .class | #id |
| JS usage | Common | Very specific |
- Use
classfor styling groups - Use
idfor unique elements
7. Using class in JavaScript (Intro)
1 2 3 4 5 6 | <p class="note">Note 1</p> <p class="note">Note 2</p> <script> let items = document.getElementsByClassName("note"); console.log(items.length); </script> |
- Selects all elements with class
note
8. Naming Rules & Best Practices
- Class names are case-sensitive
- Use meaningful names (
btn-primary,header,card) - Avoid spaces (use hyphen
-) - One word or kebab-case preferred
Bad:
<p class="red text big">
Good:
<p class="text-large text-danger">
Common Mistakes
- Using same
idinstead ofclass Forgetting dot (.) in CSS- Using spaces instead of hyphens
- Overusing too many classes unnecessarily
Key Points to Remember
classis use to style and group elementsMultiple elements can share same class
Multiple classes can be applied to one element
Selected using
.in CSSVery important for CSS & JS
