Uncategorized

Apply CSS when two classes are together

November 22, 2021

Apply CSS when two classes are together

In this article we’ll learn how to apply CSS when two classes are together, so we can activate certain styles only if this condition occurs.

Apply CSS when two classes are together cover

Hey you programmer, okay? Let’s learn how to activate some CSS rule, only if the element has two classes!

This technique is very simple and widely used

When we are going to add style to some class in CSS, we just use .ClassName

Now when we have this styling challenge with just two classes, just join the class names, like this: .firstClass.secondClass

So, we will activate the style only if the element has the two mentioned classes

Let’s see a practical example:

<!DOCTYPE html>
<html>
 <head>
  <title>Aplicar CSS quando duas classes estiverem juntas </title>
  <meta charset="utf-8">
 </head>
 <body>
  <p class="name">Matheus Budkewicz Battisti</p>
  <p class="name bold">Matheus Budkewicz Battisti</p>
 </body>
</html>

Here in this HTML structure we add two paragraphs, one contains the class name and the other name is bold.

Now let’s look at CSS using two classes:

.name.bold {
 font-weight: bold;
}

Let’s make it bold, just the paragraph that contains the name and bold classes.

Check the result:

We observe here that the result was obtained successfully, we changed the style only in the element with two classes

Also, the selector with two classes is more specific than the selector with just one of them

That is, we can override any style of the first class in the second element by joining the classes

See an example:

.name{
 color: red;
}

.name.bold {
 font-weight: bold;
 color: blue;
}

We change the color when the element combines the classes, check it out:

Conclusion

In this article we learned how to apply CSS when two classes are together

And this is very simple, we just need to create a selector with both together, like this: .classOne.classTwo

And then all styles of this rule will only be applied if the element has both determined classes

Want to learn more about CSS? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x