In CSS, classes are one of the most powerful tools for applying reusable styles to HTML elements. Whether you’re creating buttons, cards, or layouts, defining a class allows you to write clean, modular, and maintainable CSS.
This guide will teach you how to define and use a CSS class, with examples to get you started.
✅ What Is a CSS Class?
A CSS class is a named style rule that you can apply to one or more HTML elements. It starts with a dot (.
) followed by the class name, and is defined within a CSS file or <style>
block.
✅ How to Define a Class in CSS
📌 Basic Syntax:
.class-name {
property: value;
/* more properties */
}
.class-name
→ The class selector{}
→ Block containing CSS declarations
📌 Example:
.card {
background-color: #f5f5f5;
border: 1px solid #ccc;
padding: 20px;
border-radius: 8px;
}
This defines a class named card
with a light background, border, and padding.
✅ How to Apply a Class to HTML Elements
Use the class
attribute in your HTML tag to apply the style:
<div class="card">
<h3>This is a Card</h3>
<p>Reusable UI block using a CSS class.</p>
</div>
You can apply the same class to multiple elements across your page.
🧪 Applying Multiple Classes
You can apply more than one class to an element by separating them with a space:
<div class="card shadow">
<!-- This element will get styles from both .card and .shadow -->
</div>
🔧 Tips for Naming Classes
- Use meaningful names:
.error-message
,.nav-bar
,.product-card
- Avoid using HTML tag names as class names (e.g.,
.div
,.span
) - Use hyphens (
-
) for readability:.menu-item
,.text-center
🧾 Example: CSS + HTML in One Page
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p class="highlight">This paragraph is highlighted using a CSS class.</p>
</body>
</html>
🧠 Conclusion
Defining a class in CSS is simple yet powerful. It allows you to reuse styles, keep your HTML clean, and separate design from structure. Whether you’re building a small webpage or a complex application, mastering CSS classes is essential for scalable front-end development.
Pro Tip: Use classes in combination with IDs, pseudo-classes (:hover
, :focus
), and media queries for responsive and interactive designs.