0

I am having two classes, each defining on hover event. If an element contains these two classes which properties will get applied to the element.

.classA:hover{
  transform: translateX(10px);
  color: white;
}

.classB:hover{
  color: red;
}
<div class="classA classB"></div>

Would properites combine or override?

Rajat Aggarwal
  • 392
  • 3
  • 16
  • 1
    `color: red` and `transform` will work. But what stopped you from testing them yourself? :) – m4n0 Apr 03 '21 at 06:55
  • @m4n0 I want to know the rules. – Rajat Aggarwal Apr 03 '21 at 06:57
  • 3
    CSS works from top to bottom. So of course the second selector with the same specificity - https://specifishity.com/ would override the first one. – m4n0 Apr 03 '21 at 06:58
  • 1
    Basically css precedence with order. The classname to the right of multiple class override the properties before it. Within the stylesheet, the class listed last takes higher priority over the classes before it – Udendu Abasili Apr 03 '21 at 07:00

2 Answers2

3

Since both the classes have same specificity, the class which is defined later will override conflicting styles.

Thus in your example:

.classA:hover{
  transform: translateX(10px);
  color: white;
}

.classB:hover{
  color: red;
}

classB is defined later so color: red will be applied and since transform: translateX(10px) is not conflicting it will also be applied.

NOTE:

Writing either <div class="classA classB"></div> or <div class="classB classA"></div> will yield the same result.

But if the class definitions were reversed:

.classB:hover{
  color: red;
}

.classA:hover{
  transform: translateX(10px);
  color: white;
}

Then transform: translateX(10px) and color: white will be applied.

Developer
  • 425
  • 3
  • 15
1

Simple answer: Transform from ClassA and the red color from ClassB will be applied to the hover event of the element.

Not so long answer: Since ClassB comes after ClassA, it will take priority over ClassA. This is why the color from ClassB will override the color from ClassA. Since ClassA has a transform but ClassB does not the transform from ClassA gets applied to the hover event on the element. In case ClassB had a transform property too it will take priority and would override the transform in ClassA.

Hope you understand how it works now. :)

Sayan J. Das
  • 852
  • 10
  • 19
vio
  • 167
  • 9