!important(例外规则)

319 阅读1分钟

!important 与优先级无关,但它与最终的结果直接相关

一些经验法则:

  • 一定要优先考虑使用样式规则的优先级来解决问题而不是 !important
  • 只有在需要覆盖全站或外部 CSS 的特定页面中使用 !important
  • 永远不要在你的插件中使用 !important
  • 永远不要在全站范围的 CSS 代码中使用 !important
覆盖优先级高的选择器
#someElement p {color: blue;}
p.awesome {color: red;}

在外层有 #someElement 的情况下,你怎样能使 awesome 的段落变成红色呢?这种情况下,如果不使用 !important ,第一条规则永远比第二条的优先级更高

怎样覆盖 !important

A)很简单,只需再添加一条 带 !important 的CSS规则,再给这个给选择器更高的优先级(添加一个标签,ID或类);或是添加一样选择器,把它的位置放在原有声明的后面(总之,最后定义一条规则比胜)。

 table td { height: 50px !important; }
.myTable td { height: 50px !important; }
#myTable td { height: 50px !important; }