How to Select an Element with Multiple Classes in CSS?

The basic rule to select an element with multiple classes is that we have to join each class with a period(.) character without giving any space between them.

For example, if you want to select an element that has two classes class1 and class2, then you have to use .class1.class2 to select this element.

The .class1.class2 will select every element that has both classes class1 and class2.

See this working example:

Example:

.class1.class2{
   background: yellow;
}

Similarly, to select an element that has three classes, you have to join all three classes with a period(.) character. For example .class1.class2.class3

ID and Class Combination

Just like multiple classes, you can target an element that has a given id and a class both.

Put a # character before the id and a period(.) character before the class without giving any space between them to select an element that has a given id and a class.

For example, #name.yellow

The following example selects every element that has an id name and a class yellow:

Example:

#name.yellow{
   background: yellow;
}

There can be such infinite combinations of IDs and classes, you can try them out yourself.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.