何时在CSS中使用!important属性 [英] When to use the !important property in CSS

查看:123
本文介绍了何时在CSS中使用!important属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

#div p {
    color: red !important;
}
...
#div p {
    color: blue;
}

我了解!important的工作方式.在这种情况下,div将呈现红色,因为现在它具有优先级(!important).但是我仍然无法找出合适的情况来使用它.是否有一个示例,其中!important节省了一天?

I understand how !important works. In this case the div will render red because now it has priority (!important). But I can't still figure out an appropriate situation to use it in. Is there an example where !important saves the day?

推荐答案

这是现实生活中的场景

想象一下这种情况

This is the real life scenario

Imagine this scenario

  1. 您有一个全局CSS文件,用于全局设置网站的外观.
  2. 您(或其他人)在元素本身上使用内联样式,这通常是 非常不好的做法.
  1. You have a global CSS file that sets visual aspects of your site globally.
  2. You (or others) use inline styles on elements themselves which is usually very bad practice.

在这种情况下,您可以将全局CSS文件中的某些样式设置为重要样式,从而覆盖直接在元素上设置的内联样式.

In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.

当您无法完全控制HTML时,通常会发生这种情况.例如,在 SharePoint 中考虑解决方案.您希望对零件进行全局定义(样式化),但是存在一些您无法控制的内联样式. !important使这种情况更易于处理.

This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important makes such situations easier to deal with.

其他现实生活场景还包括一些写得不好的 jQuery插件,它们也使用内联样式...

Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...

我想您现在已经有了主意,并且还可以提出其他一些建议.

I suppose you got the idea by now and can come up with some others as well.

我建议您不要使用!important,除非您无法通过其他任何方式使用它.只要有可能避免它,就避免它.使用许多!important样式会使维护工作变得困难一些,因为您破坏了样式表中自然的 cascading .

I suggest you don't use !important unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.

这篇关于何时在CSS中使用!important属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆