为什么不重要!覆盖文字颜色?

时间:2019-08-29 13:01:06

标签: css css-specificity

我对下面的摘录为什么没有红色文本感到困惑。

我一直认为!important会优先于任何其他选择器,无论它的特殊性如何。不是这样吗?

.one {
  color: blue;
}

.red {
  color: red !important;
}
<div class="red">
  <div class="one">One</div>
  <div class="two">Two</div>
</div>

请明确一点,我的期望是看到只有红色文本,没有蓝色。

1 个答案:

答案 0 :(得分:1)

我在CSS中添加了另一行,以使其更加清晰。 请参见使用.bar .one更具体,然后使用.red !important,因为使用.red !important时您实际上没有为子项.one指定颜色,如果没有其他定义,它将采用该颜色。情况并非如此。

让我们将color: blue;添加到类.bar中,现在您可以看到以前定义的!important。

  

请注意,只需要!important即可覆盖内联样式!否则,!不应该使用重要的,因为它可以通过特异性解决

.red {
  color: red !important;
}

.bar, /* added ths line */
.bar .one {
  color: blue;
}
<div class="bar red">
  <div class="one">One</div>
  <div class="two">Two</div>
  Lorem red ipsum <!-- also added this line, this is red even though bar should be blue but it's overwritten with !important -->
</div>

请查看下一个代码段,并在单击“运行代码段”之前尝试找出文本的样式。

.one {
    color: red;
    font-weight: bold;
}

.one {
    color: blue !important;
    font-size: 30px;
}

.one {
    color: green;
    text-decoration: underline;
}
<p class="one" style="color: fuchsia !important;">
    What styles will I have?
</p>
    

相关问题