HTML Classes

A class is a label you attach to elements so you can style or select them together.

The same class can be reused on as many elements as you like, which is what makes classes the main tool for consistent styling across a site.

The class Attribute

Reusing a class

<!DOCTYPE html>
<html>
<head>
<style>
  .note {
    background: #fffbcc;
    padding: 8px;
    border-left: 3px solid #e6b800;
  }
</style>
</head>
<body>

<p class="note">Meeting moved to 3 PM.</p>
<p class="note">Bring your laptop charger.</p>

</body>
</html>

Why Classes Are Useful

  • Style every element with the same class in one CSS rule.
  • Give one element several classes, separated by spaces.
  • Reuse a class across the whole site for a consistent look.

Multiple Classes

Two classes at once

<!DOCTYPE html>
<html>
<head>
<style>
  .card {
    border: 1px solid #ccc;
    padding: 12px;
    border-radius: 6px;
  }
  .featured {
    border-color: #2563eb;
    background: #eff6ff;
  }
</style>
</head>
<body>

<div class="card">Standard card</div>
<div class="card featured">Featured card</div>

</body>
</html>
Note: Class names are case sensitive, so card and Card are treated as two different classes.

Exercise: HTML Classes

Which CSS selector syntax targets an HTML class?