Apply CSS when two classes are together

Asked

Viewed 17,188 times

6

How to apply a CSS setup only when a tag is with the classes nome1 and Nome2 at the same time?

I tried with the following code, but it’s not working. Does anyone know how to do?

.nome1 {
  color: black;
}

.nome2 {
  color: blue;
}

.nome3 {
  color: green;
}

.nome1 .nome2 {
  color: red;
  font-size: 18pt;
}
<div class="nome1">
  Nome1
</div>
<div class="nome2">
  Nome2
</div>
<div class="nome3">
  Nome3
</div>
<div class="nome1 nome2">
  Nome1 e Nome2
</div>

  • 1

    According to the criteria of W3schools.com you are almost right, If you added to the two 2 different colors, so it gave conflict, see this link: https://www.w3schools.com/cssref/tryit.?filename=trycss_sel_class_more2

3 answers

11


The original code is almost right. What makes the difference is that when you have a space in the style setting of CSS (.nome1 .nome2) is defining that the style will be applied to the class nome1 And nome2. You can define a rule using more than one attribute just by removing the spaces between the settings (.nome1.nome2). The result is as follows:

.nome1.nome2 {
  color: red;
  font-size: 18pt;
}

References:

3

You almost got the answer.. instead of declaring the two classes separately (.nome1 .nome2), join them in the css statement:

.nome1.nome2 {
  color: red;
  font-size: 18pt;
}

-2

When you put .nome1 .nome2, is actually saying it will be applied to the children of nome1 who are nome2

.nome1.nome2 is the right thing to do

  • After almost 4 years I expected to see a different response from the others...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.