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

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;
}

What you're actually asking is how to give a class higher specificity than an ID.

An ID has a relatively high specificity of 100. A class has a specificity of 10.

There are many ways to increase the specificity of a selector.

Here are a few methods:

#idname.classname

Now this selector has a specificity of 110.


div#idname.classname

Now this selector has a specificity of 111 (because an element has a specificity of 1).


div[class="classname"]

This selector will fail to override an ID selector, because an attribute selector has a specificity of 10, and the total specificity for the selector is only 11.


The !important annotation

While specificity applies to selectors, the !important annotation applies to the declaration. It has the power to override all specificity points.

.classname { ...  !important; }

You can think of !important as having a specificity of 10000, as illustrated in this specificity website. Although technically !important does not participate in specificity.


More information:

  • CSS Specificity
  • CSS Specificity: Things You Should Know
  • Relationship between !important and CSS specificity

You are going about this backwards. CSS rules have weight, and you should leverage those rules to correctly cascade styles.

element = 1 pt
class = 10 pt
id = 100 pt
inline = 1000 pt
!important = 10,000 pt

Consider this article on specificity

The !important clause, while it certainly works, builds inflexibility into your cascading rules and it becomes far too easy to do end up with competing directives.

My basic principle is to "generally" avoid IDs in CSS, and use them only when you need to override an existing class/element rule.

Ultimately, you are the author. Write your less specific rule as a class, and override it with an ID.

From my 14+ years building web stuff : if you have to use a !important clause, you are doing it wrong. I consider it very smelly.

That said sometimes it happens. You inherit someone else's terrible css, it can be hard to avoid.