Got confuse related to priority level of classes in css, i know the class added at the last has highest priority, but here in my case i thought i was wrong i am adding class dynamically to div, but classes are not working properly
<p>Click the button to add the "mystyle" class to DIV.</p>
<script>
function myFunction() {
document.getElementById("myDIV").classList.add("mystyle","hello");
}
</script>
<style>
.hello{
background-color: blue;
}
.mystyle {
background-color: red;
}
</style>
why div showing red color instead of blue ?
Your div
is red instead of blue because of your style declaration order:
.hello {
background-color: blue;
}
.mystyle {
background-color: red;
}
CSS specificity is not dependent on the order in which you apply the class to an element, but rather the order in which you declare the class in the style. In this case, you have declared .hello
then .mystyle
, meaning .mystyle
has high specificity compared to the .hello
and hence, you get the red background.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments