如何用外部CSS覆盖内联样式? [英] How can I override inline styles with external CSS?
问题描述
我有使用内联样式的标记,但我没有权限更改此标记。如何使用CSS覆盖内联样式在文档中?我不想使用jQuery或JavaScript。
HTML:
< div style =font-size:18px; color:red;>
Hello World,如何将颜色更改为蓝色?
< / div>
CSS:
code> div {
color:blue;
/ *这不工作* /
}
只有通过在CSS规则旁边使用!important
关键字才能覆盖内联样式。下面是一个例子。
div {color:blue!important; / *添加!important将使此规则比内联样式更优先* /}
< div style =font-size:18px; color:red;>你好,世界。如何将它改为蓝色?< / div>
重要注意事项:
使用
!important
不被视为良好做法。因此,您应该避免!important
和内联样式。
添加
!important
任何CSS规则的关键字强制规则强制超过所有其他CSS规则。
只有通过使用另一个
!important
规则,才能在CSS中使用更高的CSS特异性或等待CSS特异性
必须阅读 - CSS特异性由MDN
I have markup that uses inline styles, but I don't have access to change this markup. How do I override inline styles in a document using only CSS? I don't want to use jQuery or JavaScript.
HTML:
<div style="font-size: 18px; color: red;"> Hello World, How Can I Change The Color To Blue? </div>
CSS:
div { color: blue; /* This Isn't Working */ }
解决方案To only way to override inline style is by using
!important
keyword beside the CSS rule. Following is an example of it.div { color: blue !important; /* Adding !important will give this rule more precedence over inline style */ }
<div style="font-size: 18px; color: red;"> Hello, World. How can I change this to blue? </div>
Important Notes:
Using
!important
is not considered as a good practice. Hence, you should avoid!important
and inline style both.Adding
!important
keyword to any CSS rule forces the rule to forcefully precedes over all the other CSS rule for that element.It even overrides the inline styles from the markup.
Only way to override is by using another
!important
rule, declared either with higher CSS Specificity in the CSS or equal CSS Specificity later in the code.Must Read - CSS Specificity by MDN
这篇关于如何用外部CSS覆盖内联样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!