htmlcsscss-selectorscss-specificity

How do I give a CSS class priority over an id?


I have a element like this:

#idname{
  border: 2px solid black;
}

.classname{
  border: 2px solid gray;
}
<div id = "idname" class="classname">it is a test</div>

I want to give a bigger priority to its CSS class instead of its CSS id. Is it possible? (In other word I want to set gray-color as its border)


Solution

  • Do not use !important because it is the worst solution, if you want to switch the styling then do it that way.

    #idname{
      border: 2px solid black;
    }
    
    #idname.classname {
      border: 2px solid gray;
    }
    <div id = "idname" class="classname">it is a test</div>

    If you want to target also other elements with the class classname and not only the #idname then use:

    #idname.classname, .classname {
       border: 2px solid gray;
    }