HTML Classes
A class is a reusable label you attach to elements so CSS and JS can target them.
Naming classes well
EXAMPLE
<!-- Multiple classes on one element, separated by spaces -->
<button class='btn btn-primary btn-lg'>Save</button>
<!-- The same class on many elements -->
<article class='card'>One</article>
<article class='card'>Two</article>
<article class='card'>Three</article>
<style>
/* CSS selects by class with a dot prefix */
.card {
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 1rem;
}
.btn {
padding: 0.5rem 1rem;
border: none;
border-radius: 6px;
cursor: pointer;
}
.btn-primary { background: #2563eb; color: white; }
.btn-lg { font-size: 1.125rem; padding: 0.75rem 1.5rem; }
</style>
<script>
// JS selects by class too
document.querySelectorAll('.card').forEach((c) => {
c.addEventListener('click', () => c.classList.toggle('selected'));
});
// classList is the modern way to add, remove, toggle classes
const btn = document.querySelector('.btn');
btn.classList.add('is-loading');
btn.classList.remove('is-loading');
btn.classList.toggle('is-active');
</script>
<!-- Naming conventions worth knowing -->
<!-- BEM: block__element--modifier -->
<div class='card card--featured'>
<h3 class='card__title'>Title</h3>
</div>
<!-- Utility-first (Tailwind): each class is one rule -->
<div class='rounded-lg border p-4 bg-white'>...</div>
Why it matters
A class name should describe purpose, not appearance. `.btn-primary` survives a redesign; `.blue-button` does not. Pick one naming convention (BEM, utility-first, or your own) and stick to it across the project.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Classes</title>
</head>
<body>
<h1>HTML Classes</h1>
<p>This is a demo page for the "HTML Classes" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Add the attribute that lets CSS target this element via a class selector.
<p
="lead">Hello</p>
Five letters; same as the CSS keyword for that selector.
Discussion
Loading…