The HTML class attribute assigns one or more reusable class names to elements. Classes allow you to style multiple elements uniformly with CSS or select groups of elements with JavaScript.
You declare classes on HTML elements using the class attribute, separating multiple class names with spaces.
<!-- Assigning multiple classes -->
<div class="card card-featured dark-theme">
<h3 class="title-primary">Featured Article</h3>
</div>
In CSS, you target classes using a period (.) prefix:
.card { padding: 1rem; border-radius: 8px; }
.card-featured { border: 2px solid #38bdf8; }
Key rules for HTML classes:
class="" attribute space.btn-primary and Btn-Primary are separate names.flowchart LR
A["HTML class='btn active'"] --> B["CSS Selector (.btn)"]
A --> C["CSS Selector (.active)"]
A --> D["JS (document.querySelectorAll('.btn'))"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Classes Demonstration</title>
<style>
.badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 0.85rem; font-weight: bold; }
.badge-success { background-color: #059669; color: #ffffff; }
.badge-warning { background-color: #d97706; color: #ffffff; }
</style>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>Server Status Dashboard</h2>
<!-- Elements sharing base class and specific variant classes -->
<p>Database Node: <span class="badge badge-success">Online</span></p>
<p>Cache Worker: <span class="badge badge-warning">High Load</span></p>
</body>
</html>
.site-header, .btn-submit) rather than visual style (.blue-box, .bold-text)..card__title--large) to prevent style specificity conflicts in large applications..user-profile-card) for clean readability across HTML, CSS, and JS codebases.Create 2 <button> tags that share a common .btn class for size and padding, but have different .btn-primary and .btn-danger classes for background colors!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.