The class attribute in HTML is used to assign one or more class names to an element.
Classes help you:
<tag class="className">Content</tag>
<p class="intro">This is an introduction paragraph.</p>
<p class="intro">This is another intro paragraph.</p>
Both paragraphs share the same style when CSS is applied.
<style>
.intro {
color: green;
font-size: 18px;
}
</style>
<p class="intro">Styled paragraph using a class.</p>
Styled paragraph using a class.
You can assign more than one class:
<p class="intro highlight">This has two classes.</p>
.intro {
font-size: 18px;
}
.highlight {
background-color: yellow;
}
You can select elements by class name:
<script>
const items = document.getElementsByClassName("intro");
console.log(items);
</script>
| Feature | Class | ID |
|---|---|---|
| Usage | Many elements can share same class | Must be unique |
| CSS | .classname | #idname |
| Purpose | Styling groups of elements | Unique element identification |
| Reusable? | Yes | No |
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr>
<th>Feature</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Single Class</td>
<td>Assigning one class to an element</td>
<td><code><p class="text">...</p></code></td>
</tr>
<tr>
<td>Multiple Classes</td>
<td>Assigning more than one class</td>
<td><code><div class="box shadow"></div></code></td>
</tr>
<tr>
<td>CSS Class Selector</td>
<td>Used to style elements with a class</td>
<td><code>.text { color: blue; }</code></td>
</tr>
<tr>
<td>JS Class Selector</td>
<td>Selecting elements via JavaScript</td>
<td><code>document.getElementsByClassName("text")</code></td>
</tr>
</tbody>
</table>
Classes are one of the most important features in HTML because they: