JavaScript State vs. Class
Understanding CSS Classes
Labels for Your Styles
Imagine you're decorating a room. You decide that all the important items, like a special vase and a framed photo, should have a spotlight on them. Instead of wiring a separate light for each one, you could just label them all as "important." Then, you could set up a rule: anything labeled "important" gets a spotlight.
CSS classes work exactly like that. A class is a reusable label you can attach to any HTML element. It lets you apply the same set of styles to multiple elements without having to write the same rules over and over.
Classes are the most common way to target elements and apply styles in CSS.
To create a class, you define it in your CSS file. The name must start with a period (.). Let's create a class to make text stand out.
/* This is a CSS comment */
.important-text {
color: red;
font-weight: bold;
}
This rule says that any element with the class important-text will be red and bold. Now, we just need to attach this label to some HTML elements. We do this using the class attribute.
<p>This is a regular paragraph.</p>
<p class="important-text">This paragraph is very important.</p>
<p>This is another regular paragraph, but <span class="important-text">this part</span> is important.</p>
Combining and Overriding
An element isn't limited to just one class. You can give it multiple classes by listing them in the class attribute, separated by spaces. This is powerful because it lets you mix and match styles like building blocks.
Let's say we also have a class that adds an underline.
.underline {
text-decoration: underline;
}
We can now apply both important-text and underline to the same element to make it red, bold, and underlined.
<p class="important-text underline">This text gets styles from both classes.</p>
Use classes allow multiple elements to share styles.
What happens if two classes applied to the same element try to change the same property? For example, what if one class makes text red and another makes it blue?
This is where the "Cascading" part of Cascading Style Sheets comes in. The browser follows a set of rules to decide which style wins. One of the simplest rules is: the last class defined in the stylesheet takes precedence.
Consider this CSS:
.text-blue {
color: blue;
}
.text-red {
color: red;
}
And this HTML:
<p class="text-blue text-red">What color am I?</p>
The paragraph will be red. Because the .text-red class was defined after .text-blue in the CSS file, its color property overrides the one from .text-blue.