HTML 'class' Attribute

πŸ” What is the class Attribute in HTML?

The class attribute in HTML is used to assign one or more class names to an element. These class names can then be targeted by CSS or JavaScript to apply styles or behaviors.

>>"Classes are the glue between HTML structure and CSS design." 🎨

🧱 Syntax

You use the class attribute within an HTML tag, like so:

Basic class syntax

<div class="box">Content here</div>

🎨 Styling Classes with CSS

In CSS, you can style elements by referencing their class with a . (dot) prefix:

CSS targeting a class

.box {
  padding: 16px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
}

You can apply that class to any element:

Applying styled class in HTML

<div class="box">
  I am styled with the 'box' class!
</div>

🧾 Multiple Classes

You can assign multiple classes by separating them with spaces. This is useful for combining styles:

Multiple class names

<div class="card shadow">Multiple classes</div>

Note

⚠️ Order matters: styles from classes declared later in CSS can override earlier ones.

πŸ“ Example: Reusable Card

HTML + CSS with multiple classes

<style>
  .card {
    border-radius: 8px;
    padding: 20px;
    background-color: #fff;
  }

  .highlight {
    border: 2px solid orange;
  }
</style>

<div class="card highlight">
  This is a highlighted card.
</div>

πŸ’‘ JavaScript & Classes

JavaScript can use class names to select or modify elements dynamically.

JavaScript targeting a class

const boxes = document.querySelectorAll('.box');
boxes.forEach(el => el.style.backgroundColor = 'lightblue');

πŸ“Œ Best Practices

  • βœ… Use semantic, readable class names like btn-primary or main-header.
  • πŸ’¬ Avoid names based on presentation (e.g., red-text, big-box).
  • 🎯 Reuse class names across similar elements for consistency.

πŸ”— Further Learning

>>β€œThe class attribute bridges structure and style β€” master it and you master layout.” 🧩