Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css class priority when Adding Dynamic Class

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 ?

Working Example

like image 302
Pardeep Jain Avatar asked Oct 27 '25 20:10

Pardeep Jain


2 Answers

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.

like image 194
Kevin Avatar answered Oct 29 '25 11:10

Kevin


It is a problem of hierarchy:

function myFunction() {
    document.getElementById("myDIV").classList.add("mystyle","hello", "red-background");
}
#myDIV.hello{
background-color: blue;
}
.mystyle {
    background-color: red;
}
.mystyle {
    width: 300px;
    height: 50px;
    background-color: red;
    color: white;
    font-size: 25px;
}
<p>Click the button to add the "mystyle" class to DIV.</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and earlier versions.</p>

<div id="myDIV">
I am a DIV element
</div>
like image 29
Teuta Koraqi Avatar answered Oct 29 '25 11:10

Teuta Koraqi