learn2kode.in

HTML – Classes

The class attribute in HTML is used to assign one or more class names to an element.
Classes help you:

1. Basic Syntax

<tag class="className">Content</tag>

2. Example – Applying a Class

<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.

3. Using CSS With Classes

<style>
  .intro {
    color: green;
    font-size: 18px;
  }
</style>

<p class="intro">Styled paragraph using a class.</p>

Output

Styled paragraph using a class.

4. Multiple Classes in One Element

You can assign more than one class:

<p class="intro highlight">This has two classes.</p>

CSS Example:

.intro {
  font-size: 18px;
}

.highlight {
  background-color: yellow;
}

5. Classes in JavaScript

You can select elements by class name:

<script>
  const items = document.getElementsByClassName("intro");
  console.log(items);
</script>

6. Class vs ID (Important Difference)

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

7. HTML Class Attribute Table (Add to page)

<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>

Summary

Classes are one of the most important features in HTML because they: