To avoid the repetition of code, we use multiple classes in HTML and CSS. With CSS, we can also define and style both classes together and use multiple classes in one element by assigning them different class ids. This approach can be followed by using the space-separated syntax to add multiple classes to one HTML element.
In this article, we will learn how to add multiple classes to one element.
How to Use Multiple Classes in CSS?
To use two or more classes in one element, each class id will be separated by a space.
You have to follow the following syntax to use multiple classes in one element:
In a single HTML element, you can include more than one class by separating them with a space. For your convenience, here is an example.
Example: Using Multiple Classes in CSS
In the below example, we will create:
- A heading using the <h1> tag and assign the class name “heading”.
- Next, we will create another heading and assign it to two different classes: “heading” and “line”. These class ids are separated by a space:
HTML
</h1>
<h1 class="heading line">
Multiple Classes in One Element
</h1>
Now, let’s move to the CSS file and apply some CSS properties listed below:
- Set background color to the heading using the rgb() function as “(69, 51, 151)”.
- Set the font style “italic” for the heading.
In HTML class, the first heading utilizes the class name “heading”. So, the style specified in the specified class will be implemented on the first heading:
background-color: rgb(69, 51, 151);
font-style:italic
}
For the “line” class, we have:
- Set the color of heading using the rgb() function as “(255, 0, 0)”.
- Apply text-decoration-line as “underline”.
The second heading will utilize the styles of both classes: “heading” and “line” class:
color: rgb(255, 0, 0);
text-decoration-line:underline;
}
After implementation, check the outcome:
From the output, you can observe that the second heading utilizes both CSS classes.
Conclusion
To use multiple classes on a single element, use different class ids separated by white spaces. Using this, we can apply different CSS properties at once. It allows us to reuse the class where similar elements exist. This article explained how to use multiple classes in a single element and style it along with an example.