Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to apply two CSS classes to a single element?
We can apply multiple CSS classes to a single element by using the class attribute and separating each class with a space. This allows us to combine different styles and create more flexible, reusable CSS designs.
Syntax
/* Multiple classes in HTML */
<element class="class1 class2 class3">...</element>
/* CSS styles for each class */
.class1 { property: value; }
.class2 { property: value; }
.class3 { property: value; }
Method 1: Using the Class Attribute
The most common way to apply multiple classes is by listing them in the class attribute, separated by spaces
<!DOCTYPE html>
<html>
<head>
<title>Multiple Classes</title>
<style>
.text-red {
color: red;
}
.large-font {
font-size: 24px;
}
.bold {
font-weight: bold;
}
</style>
</head>
<body>
<p class="text-red large-font">Red and Large Text</p>
<p class="text-red bold">Red and Bold Text</p>
<p class="text-red large-font bold">Red, Large, and Bold Text</p>
</body>
</html>
Three paragraphs appear: first with red text in large font, second with red bold text, and third combining all three styles (red, large, and bold).
Method 2: Using JavaScript
You can also add multiple classes dynamically using JavaScript's classList.add() method
<!DOCTYPE html>
<html>
<head>
<title>Multiple Classes with JavaScript</title>
<style>
.highlight {
background-color: yellow;
}
.border {
border: 2px solid blue;
padding: 10px;
}
</style>
</head>
<body>
<p id="paragraph">Click the button to style this text</p>
<button onclick="applyClasses()">Apply Multiple Classes</button>
<script>
function applyClasses() {
const paragraph = document.getElementById('paragraph');
paragraph.classList.add('highlight');
paragraph.classList.add('border');
}
</script>
</body>
</html>
Initially shows plain text and a button. When the button is clicked, the paragraph gets yellow background and blue border with padding applied.
Class Precedence and Specificity
When multiple classes define the same property, CSS follows specificity rules. Classes later in the stylesheet or with higher specificity will override earlier ones
<!DOCTYPE html>
<html>
<head>
<style>
.first-color {
color: red;
font-size: 18px;
}
.second-color {
color: blue; /* This will override the red color */
}
</style>
</head>
<body>
<p class="first-color second-color">This text will be blue with 18px font size</p>
</body>
</html>
Text appears in blue color (not red) with 18px font size, demonstrating that the second class overrides the color property of the first class.
Conclusion
Applying multiple CSS classes allows for modular styling and better code reusability. Use space-separated class names in HTML or JavaScript's classList.add() method to combine multiple styles effectively.
