什么时候使用!重要属性在css? [英] when to use !important property in css?

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

问题描述

#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. Does anybody know any example where !important saves the day?

推荐答案

这是真实的生活场景



想象这种情况

This is the real life scenario

Imagine this scenario



  1. 您(或其他人)在元素自身上使用内联样式,这是通常很糟糕的做法

  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...

我想你现在有了想法

我建议你不要使用!important ,除非你不能用任何其他方式。每当有可能避免它,避免它。使用大量的!重要的样式会使维护变得更困难,因为你打破了样式表中的自然级联

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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