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

标签 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 */
}

最佳答案

覆盖内联样式的唯一方法是在 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 Notes:

  • Using !important is not considered as a good practice. Hence, you should avoid both !important and inline style.

  • Adding the !important keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.

  • It even overrides the inline styles from the markup.

  • The 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 - 如何使用外部 CSS 覆盖内联样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813220/

相关文章:

javascript - JQuery 相同的类不同的选择

css - SASS/SCSS - 制作一个选择器,将 "back out"修改选择器的父级

css - @font-face 在 Chrome (Windows) 中不显示

javascript - 有没有办法限制 Handlebars 输出中数字显示的小数位数?

css - 移动导航栏在 Foundation 中不起作用

html - :first-child not working on label (hidden radio button)

css - 为什么 <button> background-color 在应用边框后会在浏览器之间变得不一致

javascript - 使用 Flexbox 使用 overflow-x 使子 div 宽度为容器的 100%

CSS响应式设计。 2 列固定宽度。中间 div 动态宽度。在一定的窗口宽度,一列在新行

css - 有没有办法将 div 直接定位在其父级的中心?