如何用外部 CSS 覆盖内联样式?

我有使用内联样式的标记,但是我无法更改这个标记。如何只使用 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 */
}
202477 次浏览

文档中的 inline-styles具有最高的优先级,例如,如果希望将 div元素的颜色更改为 blue,但是将 inline stylecolor属性设置为 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]选择器专门选择具有 stylediv 属性

重写内联样式的唯一方法是在 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和内联样式。

  • !important关键字添加到任何 CSS 规则中,可以使用该元素的规则 强制优先于所有其他 CSS 规则

  • 它甚至从标记 覆盖内联样式

  • 覆盖的唯一方法是使用另一个 !important规则 ,在 CSS 中使用更高的 CSS 特异性声明,或者在代码后面使用相同的 CSS 特异性声明。

  • 必须读取-< a href = “ https://developer.mozilla.org/en/docs/Web/CSS/Speciity”rel = “ noReferrer”> CSS 特异性 by MDN

除了内联 !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 */
}

现在它将是 red只. . 你不能覆盖它

<div style="background: red;">
The inline styles for this div should make it red.
</div>


div[style] {
background: yellow !important;
}

以下连结载有更多资料: Http://css-tricks.com/override-inline-styles-with-css/

在 CSS 属性中使用 !important

<div style="color: red;">
Hello World, How Can I Change The Color To Blue?
</div>

div {
color: blue !important;
}

!important,在您的 CSS 声明之后。

div {
color: blue !important;


/* This Is Now Working */
}

div {
color : blue !important;
}
<div style="color : red">
hello
</div>