使用“!important"的含义是什么?在 CSS 中? [英] What are the implications of using "!important" in CSS?

查看:40
本文介绍了使用“!important"的含义是什么?在 CSS 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

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

推荐答案

是的,我会说你使用 !important 的例子是不好的做法,很可能会进一步造成不良影响下线.但这并不意味着它永远不能使用.

Yes, I'd say your example of using !important is 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.

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

Specificity is 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:

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

在此页面上,所有按钮都是黑色的.除了带有highlight"类的按钮,它们是蓝色的.除了 ID 为buyNow"的唯一按钮,它是绿色的.整个规则(在本例中为颜色和字体大小)的重要性由选择器的特殊性管理.

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.

!important 是在属性级别而不是选择器级别添加的.例如,如果我们使用这个规则:

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

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

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

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#buyNow selector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).

一个元素

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