You can apply multiple CSS classes to a single HTML element by separating the class names with a space in the class
attribute. Here’s how you can do it:
Syntax
In HTML, specify multiple classes in the class
attribute like this:
<tag class="class1 class2">Content</tag>
Each class will apply its respective styles to the element. If there are conflicting styles, the class listed later in the CSS file will take precedence due to the cascading nature of CSS.
Example
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple CSS Classes</title>
<style>
.red-text {
color: red;
}
.bold-text {
font-weight: bold;
}
</style>
</head>
<body>
<p class="red-text bold-text">This text is red and bold.</p>
<p class="red-text">This text is red but not bold.</p>
<p class="bold-text">This text is bold but not red.</p>
</body>
</html>
Result
- The first paragraph will have both red text and bold font.
- The second paragraph will have only red text.
- The third paragraph will have only bold text.
Notes
- Order of Classes: The order of the classes in the
class
attribute does not matter; all specified styles will apply unless there are conflicting rules. - Conflicting Styles: If two classes define conflicting styles, the specificity of the selectors will determine which style takes precedence. If both have equal specificity, the one defined later in the CSS file will take precedence.
- Combining Classes: You can define styles for a combination of classes by using a selector in your CSS:
.red-text.bold-text { text-transform: uppercase; }
This rule applies only when both
.red-text
and.bold-text
are applied to the same element.
By using multiple classes, you can make your styles modular and reusable, simplifying your CSS code structure.