CSS Classes: The Blueprint of Design
Writing styles directly on HTML elements (`p`, `h1`) doesn't scale. By mastering CSS Classes, you unlock the ability to create reusable, predictable, and modular styling architectures.
The Core Concept: Reusability
A CSS Class is a custom identifier you define in your stylesheet to group specific stylistic rules. Unlike HTML tags that style *all* elements of that type, classes only affect elements that explicitly declare them.
In CSS, you define a class by prefixing it with a period (.), like .card-container. In your HTML, you apply it without the dot: <div class="card-container">.
Composing UI: Multiple Classes
An HTML element isn't restricted to a single class. You can apply multiple classes to one element by separating them with spaces. This allows for powerful compositional patterns.
For example, you might have a base .btn class for structural styling (padding, borders), and modifier classes like .btn-primaryor .btn-danger for colors. This is the foundation of methodologies like OOCSS and BEM.
Classes vs. IDs
While both IDs and Classes can be used for styling, they have critical differences:
- Uniqueness: An ID (
#header) must be unique per page. A class can be used infinitely. - Specificity: IDs carry much heavier specificity weight. An ID will easily override a class rule, making your CSS harder to maintain. Always default to classes for styling!
Pro Tip: BEM Methodology+
BEM (Block, Element, Modifier) is a naming convention that makes CSS classes readable and predictable. Example: .card (Block), .card__title (Element inside the block), and .card--featured (Modifier changing the block's look). Using BEM prevents class names from colliding in large projects.
❓ Frequently Asked Questions
Why isn't my class style being applied?
1. Missing the period in CSS: Make sure you're using `.my-class` in the CSS file.
2. HTML error: Make sure you wrote `class="my-class"` in the HTML without the period.
3. Specificity: Another stronger selector (like an ID or inline styles) might be overriding your class.
Can I use numbers in a class name?
Yes, you can use numbers, but a class cannot start with a number. For example, `.box-1` is valid, but `.1box` won't work. It's best to use descriptive names (kebab-case is standard).
/* ❌ BAD */ .1-item { color: red; }/* ✅ GOOD */ .item-1 { color: red; }How do I combine multiple class selectors?
To target an element that has both classes at the same time, write them together without spaces:
/* Targets <div class="btn primary"> */ .btn.primary {background: blue;}