310

我创建了一个自定义样式表,它覆盖了我的 Wordpress 模板的原始 CSS。但是,在我的日历页面上,原始 CSS 具有使用!important声明设置的每个表格单元格的高度:

td {height: 100px !important}

有什么方法可以覆盖它吗?

4

9 回答 9

439

Overriding the !important modifier

  1. Simply add another CSS rule with !important, and give the selector a higher specificity (adding an additional tag, id or class to the selector)
  2. add a CSS rule with the same selector at a later point than the existing one (in a tie, the last one defined wins).

Some examples with a higher specificity (first is highest/overrides, third is lowest):

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

Or add the same selector after the existing one:

td {height: 50px !important;}

Disclaimer:

It's almost never a good idea to use !important. This is bad engineering by the creators of the WordPress template. In viral fashion, it forces users of the template to add their own !important modifiers to override it, and it limits the options for overriding it via JavaScript.

But, it's useful to know how to override it, if you sometimes have to.

于 2012-06-24T15:36:46.427 回答
34

除了覆盖由style属性设置的样式之外,只有在样式表中的选择器具有冲突的特性!important时才应该使用。

但即使你有冲突的特异性,最好为异常创建一个更具体的选择器。在您的情况下,最好class在您的 HTML 中有一个,您可以使用它来创建一个不需要!important规则的更具体的选择器。

td.a-semantic-class-name { height: 100px; }

我个人从不!important在我的样式表中使用。请记住,CSS 中的 C 用于级联。使用!important将打破这一点。

于 2012-09-17T09:12:22.437 回答
23

免责声明:不惜一切代价避免 !important 。

这是一个肮脏的,肮脏的黑客,但是您可以通过在您尝试覆盖重要的属性上使用(无限循环或非常持久的)动画来覆盖!重要,没有!重要。

@keyframes forceYellow {
  from {
    background-color: yellow;
  }
  to {
    background-color: yellow;
  }
}

div {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background: red !important;
  animation: 1s linear infinite forceYellow;
}
<div></div>

于 2017-12-14T00:47:26.713 回答
19

好的,这是关于 CSS 重要性的快速课程。我希望下面的帮助!

首先,样式的每个部分都以权重命名,因此与该样式相关的元素越多,它就越重要。例如

#P1 .Page {height:100px;}

比以下更重要:

.Page {height:100px;}

因此,当使用重要时,理想情况下,应该只在真正需要时才使用它。所以要覆盖 decleration,使样式更具体,但也要有覆盖。见下文:

td {width:100px !important;}
table tr td .override {width:150px !important;}

我希望这有帮助!!!

于 2014-05-18T19:12:44.070 回答
13

使用 JavaScript 覆盖

$('.mytable td').attr('style', 'display: none !important');

为我工作。

于 2014-10-09T11:01:42.270 回答
6

这也有帮助

td[style] {height: 50px !important;}

这将覆盖任何内联样式

于 2016-08-31T14:02:03.817 回答
3

height在任何情况下,您都可以使用覆盖max-height

于 2019-12-05T22:04:22.190 回答
2

您可以通过在选择器中上升来使用更高的特异性。

td {height: 100px !important}
/* higher precedence */
table td {height: 200px !important}

您可以在此处查看有关如何覆盖 css 的详细文章

于 2021-10-17T06:31:59.397 回答
-4

我想添加一个尚未提及的答案,因为我已尝试上述所有方法均无济于事。我的具体情况是我使用的是semantic-ui,它!important在元素上内置了属性(非常烦人)。我尝试了一切来覆盖它,最后只有一件事起作用(使用jquery)。如下:

$('.active').css('cssText', 'border-radius: 0px !important');
于 2016-10-26T13:25:31.570 回答