Basic Syntax
<element class="class-name">Content</element>Example: Reusing a Class
<h2 class="section-title">Our Courses</h2>
<p class="section-description">Learn practical web development.</p>
<h2 class="section-title">Our Projects</h2>
<p class="section-description">Explore real-world examples.</p>The same class can be assigned to many elements. This makes classes useful for reusable styles and component patterns.
Using Classes in CSS
CSS uses a period (.) before a class name.
<style>
.section-title {
color: #1d4ed8;
font-size: 28px;
}
.section-description {
color: #555;
line-height: 1.6;
}
</style>Every element with the corresponding class can receive the defined styles.
Multiple Classes on One Element
An element can have several classes. Separate the class names with whitespace.
<button class="button primary large">
Start Learning
</button>This element has three classes:
buttonprimarylarge
Each class can contribute different styles or behavior.
<style>
.button {
padding: 10px 16px;
border: 0;
border-radius: 6px;
}
.primary {
background: #1d4ed8;
color: white;
}
.large {
font-size: 18px;
}
</style>Adding and Removing Classes with JavaScript
JavaScript provides classList to manage classes without replacing the entire class attribute manually.
<button id="toggle-button" class="button">
Toggle Highlight
</button>
<p id="target" class="message">
This message can be highlighted.
</p>
<style>
.highlight {
background: #fff3a3;
padding: 8px;
}
</style>
<script>
const button = document.getElementById("toggle-button");
const target = document.getElementById("target");
button.addEventListener("click", function () {
target.classList.toggle("highlight");
});
</script>When the button is clicked, JavaScript adds the highlight class if it is absent or removes it if it is present.
Useful classList Methods
classList.add("name")— adds a class.classList.remove("name")— removes a class.classList.toggle("name")— toggles a class.classList.contains("name")— checks whether a class exists.classList.replace("old", "new")— replaces a class when the old class is present.
For example:
element.classList.add("active");
if (element.classList.contains("active")) {
console.log("The element is active.");
}
element.classList.remove("active");