Win*_*ash 21 html css stylesheet
我正在尝试的是在元素上设置此CSS
background: red !important;
Run Code Online (Sandbox Code Playgroud)
所以,当我尝试这样做.
background: yellow;
Run Code Online (Sandbox Code Playgroud)
(我没有使用外部css)它仍然只显示那个字段的红色而不是黄色,就像我希望的那样.
我问的是如何覆盖它,是否可能?
Nul*_*teя 33
可以覆盖Ans是YES, !important
但不能通过!important
正常声明覆盖.它必须比所有其他声明更高的特异性.
但是,它可以用更高的特异性!important
声明覆盖.
Firefox解析器中的这段代码片段将解释它的工作原理:
if (HasImportantBit(aPropID)) {
// When parsing a declaration block, an !important declaration
// is not overwritten by an ordinary declaration of the same
// property later in the block. However, CSSOM manipulations
// come through here too, and in that case we do want to
// overwrite the property.
if (!aOverrideImportant) {
aFromBlock.ClearLonghandProperty(aPropID);
return PR_FALSE;
}
changed = PR_TRUE;
ClearImportantBit(aPropID);
}
Run Code Online (Sandbox Code Playgroud)
好读
这是一个展示如何覆盖CSS的示例
HTML
<div id="hola" class="hola"></div>
Run Code Online (Sandbox Code Playgroud)
CSS
div { height: 100px; width: 100px; }
div { background-color: green !important; }
.hola{ background-color:red !important; }
#hola{ background-color:pink !important;}
Run Code Online (Sandbox Code Playgroud)
和输出将是
我们也不能覆盖内联 !important
HTML
<div id="demo" class="demo" style="background-color:yellow !important;"></div>
Run Code Online (Sandbox Code Playgroud)
CSS
div { height: 100px; width: 100px; }
div { background-color: green !important; }
.demo{ background-color:red !important; }
#demo{ background-color:pink !important;}
Run Code Online (Sandbox Code Playgroud)
输出是
o.v*_*.v. 15
如w3规范中所述,!important
声明不会改变特异性,而是优先于"正常"声明.实际上,这样的声明只能在它们之间"竞争" - 因此,你可以用另一个!important
更高特异性的声明覆盖你的声明:
/*
these below are all higher-specificity selectors and, if both
rules are applicable to the same element, background colour
will be set to "yellow":
*/
.some-class.some-other-class, div.some-class, #some-id {background: yellow !important;}
.some-class {background: red !important;}
Run Code Online (Sandbox Code Playgroud)
还有一个需要考虑的声明顺序 - 如果CSS的选择器具有相同的特异性,那么CSS中的声明将优先于先前的声明.
一个值得注意的案例是它与内联声明发生冲突.违反直觉(但完全符合规范),!important
价值将出现在最前面!这意味着,如果你有
<style>
#secret-container {display:none !important;}
</style>
<script>
$('#secret-container').show();//using jQuery etc.
</script>
<div id="secret-container">...</div>
Run Code Online (Sandbox Code Playgroud)
有问题的div将保持隐藏状态!内联规则优先于一个规则的唯一方法!important
是,也可以通过应用!important
它来实现.我会让你判断practice_ಠ的做法有多好
Chr*_*ill 12
!important
将覆盖background: yellow;
尝试避免使用!important
.看看css特异性.http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/