HTML Class Attribute


What is the class Attribute?

The class attribute in HTML is used to assign one or more class names to an HTML element. These class names can then be used in CSS and JavaScript to style or manipulate the element.


Syntax

<tag class="class-name">Content</tag>

You can assign multiple class names by separating them with spaces:

<tag class="class1 class2">Content</tag>

Purpose of class

  • CSS Styling – Apply styles to elements with the same class.
  • JavaScript Targeting – Easily select and manipulate elements.
  • Reusable Code – Apply the same formatting to multiple elements.

Examples of Use

Styling with CSS

.red-text {
  color: red;
}
.bold {
  font-weight: bold;
}

Then use it in HTML:

<p class="red-text bold">This is red and bold</p>

Targeting with JavaScript

document.querySelector('.red-text').style.fontSize = '20px';

Best Practices

  • Use lowercase for class names (.menu, .nav-bar)
  • Use hyphens for multi-word class names (.main-content)
  • Keep names descriptive and semantic
  • Reuse classes where possible instead of duplicating styles