我有一些使用内联样式的标记,但我无法更改这些标记。如何仅使用CSS覆盖文档中的内联样式?我不想使用jQuery或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 */
}
我有一些使用内联样式的标记,但我无法更改这些标记。如何仅使用CSS覆盖文档中的内联样式?我不想使用jQuery或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 */
}
覆盖内联样式的唯一方法是在CSS规则旁边使用!important
关键字。以下是一个例子。
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
不被视为良好实践。因此,您应该避免同时使用!important
和内联样式。为任何CSS规则添加
!important
关键字都会让该规则 强制优先于该元素的所有其他CSS规则。它甚至还会覆盖来自标记的内联样式。
覆盖的唯一方法是使用另一个
!important
规则,在CSS中具有更高的特殊性或在代码后面具有相等的特殊性声明。必读 - 由MDN提供的CSS特殊性文档
内联样式
具有最高优先级。例如,如果您想将div
元素的颜色更改为blue
,但是您有一个内联样式
,其中设置了color
属性为red
。<div style="font-size: 18px; color: red;">
Hello World, How Can I Change The Color To Blue?
</div>
div {
color: blue;
/* This Won't Work, As Inline Styles Have Color Red And As
Inline Styles Have Highest Priority, We Cannot Over Ride
The Color Using An Element Selector */
}
那么,我应该使用jQuery/Javascript吗?答案是不
我们可以使用element-attr
CSS选择器与!important
,请注意,这里!important
很重要,否则它将无法覆盖内联样式..
<div style="font-size: 30px; color: red;">
This is a test to see whether the inline styles can be over ridden with CSS?
</div>
div[style] {
font-size: 12px !important;
color: blue !important;
}
注意:仅使用
!important
在这里可以工作,但我已经使用了div[style]
选择器来专门选择具有style
属性的div
!important
则不能(据我所知)。 - Tony您可以轻松覆盖内联样式,除了内联!important
样式。
因此,
<div style="font-size: 18px; color: red;">
Hello World, How Can I Change The Color To Blue?
</div>
div {
color: blue !important;
/* This will Work */
}
但是如果你有
<div style="font-size: 18px; color: red !important;">
Hello World, How Can I Change The Color To Blue?
</div>
div {
color: blue !important;
/* This Isn't Working */
}
红色
..而且你无法覆盖它。!important
时的行为,其他答案中没有涉及到这一点。这可能不是一个完全独立的答案,但它与其他提供的答案不同。 - grg<div style="background: red;">
The inline styles for this div should make it red.
</div>
div[style] {
background: yellow !important;
}
在你的CSS声明中使用!important
div {
color: blue !important;
/* This Is Now Working */
}
div {
color : blue !important;
}
<div style="color : red">
hello
</div>
!important
。<div style="color: red;">
Hello World, How Can I Change The Color To Blue?
</div>
div {
color: blue !important;
}