简体   繁体   English

CSS *覆盖类的样式

[英]CSS * overriding class style

I'm having some difficulty with applying CSS. 我在应用CSS时遇到了一些困难。 I have a text color specified in a global external style sheet, which uses * to apply the color. 我在全局外部样式表中指定了文本颜色,该样式表使用*来应用颜色。 I'm now trying to override this for one specific class. 我现在正尝试针对一个特定的类重写此内容。 I've tried setting the text color for the class within the header of the document (which if I'm correct should override the external sheet?), however the color will not change. 我尝试在文档的标题内设置类的文本颜色(如果我正确的话,应覆盖外部工作表?),但是颜色不会改变。

Google chrome inspector shows me that * is still dominating the class specification. Google chrome检查器向我显示*仍在主导类规范。 Any ideas? 有任何想法吗?

My external style sheet looks like this: 我的外部样式表如下所示:

* {
  font-size: 14px;
  color: #666;
 }

and my header style looks like this: 我的标题样式如下:

.error-list {
   color: red !important;
}

Its worth mentioning that I've tried it with and without the !important. 值得一提的是,无论有没有!important我都尝试过。

Try making your CSS rule more specific. 尝试使您的CSS规则更具体。 For example if your .error-list is made of li tags. 例如,如果您的.error-list由li标签组成。 Change your CSS rule to .error-list li to make it more specific. 将您的CSS规则更改为.error-list li以使其更加具体。

It all comes down to which has higher specificity . 归结为具有更高的特异性

In below sample the span and the error-list rule has higher specificity than * , but the div.error-list has even higher than the error-list , so even if the error-list is placed after in the CSS, the highest wins (as with the first div in below sample). 在下面的示例中, spanerror-list规则的特异性比* ,但是div.error-list甚至比error-list更高,因此即使将error-list放在CSS中,也能赢得最高的收益(与下面示例中的第一个div )。

To override 覆盖

 * { font-size: 14px; color: #666; } span { color: red; } div.error-list { color: blue; } .error-list { color: red; } 
 <span>Hey, I'm red</span> <div class="error-list">Hey, I'm <strike>red too</strike> blue</div> <div class="error-list">Hey, I'm blue</div> 

To override a higher specificity, one can use !important , below done on the 2 error-list (compare result with the first sample above). 要覆盖更高的特异性,可以使用!important ,下面对2个error-list (将结果与上面的第一个示例进行比较)。

 * { font-size: 14px; color: #666; } span { color: red; } div.error-list { color: blue; } .error-list { color: red !important; } 
 <span>Hey, I'm red</span> <div class="error-list">Hey, I'm <strike>red too</strike> blue</div> <div class="error-list">Hey, I'm blue</div> 

When you inspect it, do you see the class you created? 当您检查它时,您看到创建的类了吗? Maybe its not there at all. 也许根本不存在。

Its hard to tell without the code but anyway !important can override the global class. 没有代码很难说,但是无论如何!important可以覆盖全局类。 Also inline css would override it but since you need to reuse it as a class this is not recommended 此外,内联css会覆盖它,但是由于您需要将其作为类重用,因此不建议这样做

try this: 尝试这个:

element[style] { /*don't change the style*/
   color: red!important;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM