Html 在 CSS 中使用“!important”有什么含义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3706819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:29:43  来源:igfitidea点击:

What are the implications of using "!important" in CSS?

htmlcsscss-specificity

提问by Kyle

I've been working on a website for a few months, and a lot of times when I've been trying to edit something, I have to use !important, for example:

我已经在一个网站上工作了几个月,很多时候当我试图编辑某些东西时,我必须使用!important例如

div.myDiv { 
    width: 400px !important;
}

in order to make it display as expected. Is this bad practice? Or is the !importantcommand okay to use? Can this cause anything undesired further down the line?

以使其按预期显示。这是不好的做法吗?或者!important命令可以使用吗?这会导致任何不受欢迎的事情吗?

回答by Stephan Muller

Yes, I'd say your example of using !importantis bad practice, and it's very likely it would cause undesired effects further down the line. That doesn't mean it's never okay to use though.

是的,我会说您的使用示例!important是不好的做法,并且很可能会进一步产生不良影响。这并不意味着它永远不会使用。

What's wrong with !important:

有什么问题!important

Specificityis one of the main forces at work when the browser decides how CSS affects the page. The more specific a selector is, the more importance is added to it. This usually coincides with how often the selected element occurs. For example:

当浏览器决定 CSS 如何影响页面时,特异性是起作用的主要力量之一。选择器越具体,其重要性就越高。这通常与所选元素出现的频率一致。例如:

button { 
    color: black; 
}
button.highlight { 
    color: blue; 
    font-size: 1.5em;
}
button#buyNow { 
    color: green; 
    font-size: 2em;
}

On this page, all buttons are black. Except the buttons with the class "highlight", which are blue. Except that one unique button with the ID "buyNow", which is green. The importance of the entire rule (both the color and font-size in this case) is managed by the specificity of the selector.

在此页面上,所有按钮均为黑色。除了带有“highlight”类的按钮,它们是蓝色的。除了唯一一个 ID 为“buyNow”的按钮,它是绿色的。整个规则的重要性(在这种情况下是颜色和字体大小)由选择器的特殊性管理。

!important, however, is added at a property level, not a selector level. If, for instance, we used this rule:

!important但是,是在属性级别而不是选择器级别添加的。例如,如果我们使用以下规则:

button.highlight {
    color: blue !important;
    font-size: 1.5em;
}

then the color property would have a higher importance than the font-size. In fact, the color is more important than the color in the button#buyNowselector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).

那么颜色属性将比字体大小具有更高的重要性。事实上,颜色比button#buyNow选择器中的颜色更重要,而不是字体大小(它仍然由常规 ID 与类特异性控制)。

An element <button class="highlight" id="buyNow">would have a font-size of 2em, but a color blue.

元素<button class="highlight" id="buyNow">的字体大小为2em,但颜色为blue

This means two things:

这意味着两件事:

  1. The selector does not accurately convey the importance of all the rules inside it
  2. The onlyway to override the color blue is to use another!importantdeclaration, for example in the button#buyNowselector.
  1. 选择器没有准确传达其中所有规则的重要性
  2. 覆盖蓝色的唯一方法是使用另一个!important声明,例如在button#buyNow选择器中。

This not only makes your stylesheets a lot harder to maintain and debug, it starts a snowball effect. One !importantleads to another to override it, to yet another to override that, et cetera. It almost never stays with just one. Even though one !importantcan be a useful short-term solution, it will come back to bite you in the ass in the long run.

这不仅使您的样式表更难维护和调试,而且会引发滚雪球效应。一个!important导致另一个覆盖它,另一个覆盖它,等等。它几乎从不只留一个。尽管它!important可以是一个有用的短期解决方案,但从长远来看,它会回来咬你的屁股。

When is it okay to use:

什么时候可以使用:

  • Overriding styles in a user stylesheet.
  • 覆盖用户样式表中的样式。

This is what !importantwas invented for in the first place: to give the user a means to override website styles. It's used a lot by accessibility tools like screen readers, ad blockers, and more.

这就是!important最初发明的目的:为用户提供覆盖网站样式的方法。它被屏幕阅读器、广告拦截器等辅助工具大量使用。

  • Overriding 3rd party code & inline styles.
  • 覆盖第 3 方代码和内联样式。

Generally I'd say this is a case of code smell, but sometimes you just have no option. As a developer, you should aim to have as much control over your code as possible, but there are cases when your hands are tied and you just have to work with whatever is present. Use !importantsparingly.

通常我会说这是代码异味的情况,但有时您别无选择。作为开发人员,您的目标应该是尽可能多地控制您的代码,但在某些情况下,您的双手被束缚,您只需要处理现有的任何内容。使用!important谨慎。

  • Utility classes
  • 实用程序类

Many libraries and frameworks come with utility classes like .hidden, .error, or .clearfix. They serve a single purpose, and often apply very few, but very important, rules. (display: nonefor a .hiddenclass, for example). These should override whatever other styles are currently on the element, and definitely warrant an !importantif you ask me.

许多图书馆和框架配备了实用工具类喜欢.hidden.error.clearfix。它们服务于单一目的,并且通常适用很少但非常重要的规则。(例如,display: none对于一个.hidden班级)。这些应该覆盖当前元素上的任何其他样式,!important如果你问我,绝对保证。

Conclusion

结论

Using the !importantdeclaration is often considered bad practice because it has side effects that mess with one of CSS's core mechanisms: specificity. In many cases, using it could indicate poor CSS architecture.

使用!important声明通常被认为是不好的做法,因为它的副作用会干扰 CSS 的核心机制之一:特异性。在许多情况下,使用它可能表示糟糕的 CSS 架构。

There are cases in which it's tolerable or even preferred, but make sure you double check that one of those cases actually applies to your situation before using it.

在某些情况下,它是可以容忍的,甚至是首选的,但请确保在使用之前仔细检查其中一种情况是否确实适用于您的情况。

回答by Delan Azabani

!importantforces the statement to always apply, doing these things:

!important强制语句始终适用,执行以下操作:

  • even if the selector is less specific and lower level, it now beats higher specificity selectors
  • if there are further occurrences of that statement that would normally override that one, it does not override the important statement any more
  • 即使选择器的特定性较低且级别较低,它现在也能胜过更高特定性的选择器
  • 如果该语句进一步出现通常会覆盖该语句,则它不再覆盖重要语句

Most of the time, !importantcan be avoided because specificity of selectors handles which one takes effect, which is the idea of cascading styles. However, there are some situations (can't quite remember the exact one) where the specificity isn't that logical and I have to force !importanton the statement.

大多数时候,!important可以避免,因为选择器的特殊性处理哪个生效,这就是级联样式的想法。但是,在某些情况下(不太记得确切的情况),其中的特殊性不是那么合乎逻辑,我必须强行!important声明。

Reasons not to use/avoid !important?

不使用/避免的原因!important

  • prevents users from using custom stylesheets (which now can't override the rules that are marked as important) which breaks accessibility for some people
  • makes code more difficult to read because the mind normally takes specificity quite easily, but remembering what is !importantmakes it harder to read
  • 阻止用户使用自定义样式表(现在不能覆盖标记为重要的规则),这会破坏某些人的可访问性
  • 使代码更难阅读,因为大脑通常很容易获得特定性,但记住什么!important会使它更难阅读

回答by osirisgothra

I think it is important that we touch on this again, here at the end of 2014 when more rules are being added into the working draft, it is so important not to impose restrictions upon your users. I have wrtten this small example to explain a possible scenario in which such a thing takes place. This is taken from a REAL website I have visited on the web, and I see it, sadly, more often than not.

我认为我们再次讨论这一点很重要,在 2014 年底,当更多规则被添加到工作草案中时,不要对您的用户施加限制非常重要。我写了这个小例子来解释发生这种事情的可能场景。这是从我在网上访问过的一个真实网站上截取的,遗憾的是,我经常看到它。

Form Text Editor Fields

表单文本编辑器字段

You have a website, and your website depends on filling out forms and editing text. To try to minimize eye strain you try to go with a style you think everyone will be okay with, and since your users mainly visit at night, you decide to make your background color to be white, and then make the text color to be black. The form is blank by default, so you type in text (this time) to make sure it works:

您有一个网站,您的网站依赖于填写表格和编辑文本。为了尽量减少眼睛疲劳,您尝试采用您认为每个人都可以接受的样式,并且由于您的用户主要在晚上访问,因此您决定将背景颜色设为白色,然后将文本颜色设为黑色. 表单默认为空白,因此您输入文本(这次)以确保其有效:

...
background-color: black; /* I forgot important here, but it works fine on its own */
color: white !important;
...

A few months later, users complain that white-on-black is too eye straining but the other half love it, what do you do? you add a custom theme that uses !important to override the internal styles so that BOTH parties are happy, which is what it is SUPPOSED to be used for:

几个月后,用户抱怨黑底白字太费眼,但另一半喜欢它,你怎么办?您添加了一个使用 !important 覆盖内部样式的自定义主题,以便双方都满意,这就是它应该用于:

...
background-color: white !important;   
color: black !important;
...

Now, what happens here? What did you expect. If you properly remember the !important tags in the first set, you would have noticed it didn't work and probably remembered that you needed to delete the !important tags off. BUT you forgot one..

现在,这里发生了什么?你期待什么。如果您正确记住了第一组中的 !important 标签,您会注意到它不起作用,并且可能记得您需要删除 !important 标签。但是你忘记了一个..

RIGHT, you get white text on white background, and the user can no longer read your webpage at all if they try to use this new style (assuming you kept it).

对,您会在白色背景上看到白色文本,如果用户尝试使用这种新样式(假设您保留它),则他们根本无法再阅读您的网页。

Of course, You don't realize this because the textbox is empty. And You ASSUME that it will work! (Assumption is a developer's worst enemy, it's right up there with pride and arrogance).

当然,您没有意识到这一点,因为文本框是空的。你假设它会起作用!(假设是开发人员最大的敌人,它的骄傲和傲慢就在那里)。

Make and Follow Self Implied Rules

制定并遵循自我暗示的规则

So, the basic rule should be only use !important when designing OVERRIDES to an original completeset of css rules. Remember that it is meant for exceptions and disturbs the natural order and meaning of css in the first place. In MOST cases you will not need to use it at all.

因此,在将 OVERRIDES 设计为原始的完整css 规则集时,基本规则应该只使用 !important 。请记住,它首先用于异常并扰乱了 css 的自然顺序和含义。在大多数情况下,您根本不需要使用它。

Know How Users Customize Their Colors

了解用户如何自定义颜色

With the existence of such tools as extensions and the presence of sites like 'userstyles.org' and it's stylish counterpart, you run the risk of alienating your users by using the !important tag at all! Keep in mind that stylish will not override them.

随着诸如扩展程序之类的工具的存在以及诸如“userstyles.org”之类的网站的存在以及它的时尚对应物,您可能会因为使用 !important 标签而疏远您的用户!请记住,时尚不会覆盖它们。

Never Restrict Your Visitors

永远不要限制您的访客

If you use !important on a style, make sure you make it possible for the user to turn that style off (and i dont mean via the web browser's internal 'on/off' switch). And for heavens sake don'tmake it DEFAULT.

如果您在样式上使用 !important,请确保您可以让用户关闭该样式(我的意思不是通过网络浏览器的内部“开/关”开关)。看在上帝的份上,不要让它成为默认值。

Ads

广告

People are less and less using stylish for ad removal, so I don't think protecting ads with !important really is an issue here. It will just annoy someone trying to customize your site.

人们越来越少地使用时尚来去除广告,所以我认为用 !important 保护广告在这里真的不是一个问题。它只会惹恼试图自定义您的网站的人。

回答by garrettmac

A little late to this question but it's saying "no matter what other styles are applied, ignore them and use this one". You may find it a little confusing with the !infront (of the !important) because thats a not operator in javascript but in css it's called a delimiter token that just says to take priority. Heres an example.

这个问题有点晚了,但它说“无论应用什么其他样式,忽略它们并使用这个”。您可能会发现它与!前面(的!important)有点混淆,因为那是 javascript 中的 not 运算符,但在 css 中它被称为分隔符标记,只是说要优先。这是一个例子。



Without !important:

没有!important

.set-color{
  color: blue;
 }

.set-color{
  color: red;
 }

outputs RED

输出红色



!importanton bottom attribute(of same)

!important底部属性(相同)

.set-color{
  color: blue;
 }

.set-color{
  color: red !important;
 }

outputs RED(would have been red anyways)

输出红色(无论如何都会是红色的)



!importanton top attribute(of same)

!important在顶部属性(相同)

.set-color{
  color: blue !important;
 }

.set-color{
  color: red;
 }

outputs BLUE(says ignore red, use blue)

输出蓝色(说忽略红色,使用蓝色)



回答by gianebao

For me, using !importantis a bad CSS practice. It disrupts the natural flow in applying the css rules where in properties are applied from top to bottom. With !important, the property will now give priority to the latest important value.

对我来说,使用!important是一种糟糕的 CSS 实践。它破坏了应用 css 规则的自然流程,其中 in 属性从上到下应用。使用!important,该属性现在将优先考虑最新的重要值。

It's just like using the gotokeyword in scripts. Though its are perfectly legal, it's still best avoided.

这就像goto在脚本中使用关键字一样。虽然它是完全合法的,但仍然最好避免。

回答by Sidharth Panwar

I wouldn't advise you to use it unless it's a necessity, which sometimes might be the case with you, as you're working on an existing project. But try to stay away from it and use as little !important as possible.

我不建议您使用它,除非它是必要的,有时您可能会遇到这种情况,因为您正在处理现有项目。但是尽量远离它并尽可能少地使用 !important 。

The problem is if you use too many of them then one might inadvertently overwrite the other. Your code is also much less legibleand anyone who comes after you to maintain this will tear his/her hair apart, as trying to find !important every time you do something in the CSS is a royal pain.

问题是,如果您使用太多它们,那么一个可能会无意中覆盖另一个。你的代码也不太清晰,任何在你之后维护它的人都会撕毁他/她的头发,因为每次你在 CSS 中做某事时都试图找到 !important 是一种巨大的痛苦。

Check this: http://webdesign.about.com/od/css/f/blcssfaqimportn.htm

检查这个:http: //webdesign.about.com/od/css/f/blcssfaqimportn.htm

回答by Emanuel Pietri

Well, i think using !importantis sometime "must to do job" if you want overdraw wp-plugins default properties.

好吧,我认为!important如果你想透支 wp-plugins 的默认属性,使用有时是“必须做的工作”。

I used it just today and it was the only way to finish my job. Maybe is not good way to do something but sometime is the only way to do it.

我今天才使用它,这是完成我的工作的唯一方法。也许不是做某事的好方法,但有时是唯一的方法。

回答by gdfgdfg

The problem with !importantis that with CSSyou MUST in all cases try to avoid deep selecting (more priority), because in the future you or someone else (often for big projects) will need to override these styles WITHOUT changing the original style and then this one will have limited freedom to do that. He will need to use !important, too with deeper selector.

问题!important在于CSS你必须在所有情况下都尽量避免深度选择(更优先),因为将来你或其他人(通常用于大项目)将需要覆盖这些样式而不改变原始样式,然后是这个样式将有有限的自由来做到这一点。他将需要使用!important, 也有更深的选择器。

回答by PIZZZZZZZZZZZA is here

!important is a factor, That can vain your code for something that is overridden

!important 是一个因素,这可能会使您的代码因被覆盖的内容而无效

the ! in it does not mean Logical not, such here it gets disconcerting with that among that code. !important is frequently a colossal mishap in computing.

这 !在这并不意味着逻辑上没有,因此在这里它与该代码中的那个令人不安。!important 经常是计算中的一个巨大事故。

For Example if you want to make it display: block;but you've already defined display: none;:

例如,如果你想制作它display: block;但你已经定义了display: none;

p {
   display: none;
   display: block !important /*Now overriden*/;
}
<p>Some Paragraph</p>

!importantis a best avoided keyword, When to use it, It may be a Influential time, Please click this link to see when to use !important, !important Style Rule - CSS-Tricks

!important是一个最好避免的关键字,何时使用它,这可能是一个有影响力的时间,请单击此链接查看何时使用!important!important Style Rule - CSS-Tricks

Avoid using !important

避免使用 !important

no madder what

没什么意思