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

穿精又带淫゛_ 提交于 2019-11-27 09:21:42

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:

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.

A little other workaround solution that in some cases could help is to use

div[id=idname]{
   border: 2px solid black;
}
.classname{
   border: 2px solid grey;
}

I needed it in a drag&drop little game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!