Learn HTML – Part 50 – class Attribute – Grouping HTML Elements
The HTML class attribute is used to group multiple HTML elements together.
Unlike the id attribute, which must be unique, the class attribute can be used on many elements.
What is the class Attribute?
The class attribute assigns a class name to one or more HTML elements.
These elements can then be styled together using CSS or manipulated using JavaScript.
Basic Syntax
<element class="className">Content</element>
Multiple elements can share the same class name.
Example – Using class Attribute
<p class="intro">Welcome to HTML learning.</p>
<p class="intro">This is another paragraph with the same class.</p>
Output:
Welcome to HTML learning.
This is another paragraph with the same class.
Using class with CSS
The class attribute is commonly used in CSS to style multiple elements.
<style>
.intro {
color: green;
font-weight: bold;
}
</style>
<p class="intro">Styled text</p>
<p class="intro">Another styled paragraph</p>
Output:
Styled text
Another styled paragraph
Using Multiple Classes
An element can have more than one class name.
<p class="text highlight">Important message</p>
Multiple classes allow combining different styles.
Difference Between id and class
| Feature | id | class |
|---|---|---|
| Usage | Unique element | Multiple elements |
| Reusability | Used once per page | Used many times |
| CSS Selector | #idName | .className |
Why Use class?
- Groups multiple elements together
- Applies the same style to many elements
- Helps organize large HTML documents
- Widely used in CSS frameworks
The
classattribute groups HTML elements so they can share styles and behaviors.
Common Mistakes Beginners Make
- Using id instead of class for multiple elements
- Using unclear class names
- Forgetting that class names are case-sensitive in CSS
Conclusion
The HTML class attribute is used to group multiple elements so they can share the same styles or behavior.
It is one of the most important attributes used in HTML, especially when working with CSS and JavaScript.
What’s Next?
Now that you understand the class attribute, the next step is learning about global attributes, which are attributes that can be used on most HTML elements.
Next: Learn HTML – Part 51 – Global Attributes in HTML →
Series: Learn HTML Series
