CSS !important 规则
什么是 !important?
CSS 中的 !important
规则用于比普通属性/值添加更高的重要性。
事实上,如果您使用 !important
规则,它将覆盖该元素上针对该特定属性的所有先前样式规则!
让我们看一个例子
示例
#myid {
background-color: blue;
}
.myclass {
background-color: gray;
}
p {
background-color: red !important;
}
示例解释
在上面的例子中,所有三个段落都会获得红色背景颜色,即使 ID 选择器和类选择器具有更高的特异性。 !important
规则会覆盖这两种情况下的 background-color
属性。
关于 !important 的重要提示
覆盖 !important
规则的唯一方法是在源代码中包含另一个具有相同(或更高)特异性的声明的 !important
规则 - 问题就在这里开始!这会使 CSS 代码混乱,并且调试会很困难,尤其是当您有大型样式表时!
这里我们创建了一个简单的示例。从 CSS 源代码上看,不清楚哪种颜色被认为最重要
示例
#myid {
background-color: blue !important;
}
.myclass {
background-color: gray !important;
}
p {
background-color: red !important;
}
提示: 了解 !important
规则很重要。您可能会在某些 CSS 源代码中看到它。但是,除非绝对必要,否则请勿使用它。
或许一两个合理使用 !important 的情况
使用 !important
的一种方法是,如果您必须覆盖一种无法以任何其他方式覆盖的样式。如果您正在处理内容管理系统 (CMS) 并且无法编辑 CSS 代码,则可能需要这样做。然后,您可以设置一些自定义样式来覆盖 CMS 的某些样式。
另一种使用 !important
的方法是:假设您想让页面上的所有按钮都具有特殊的外观。这里,按钮使用了灰色背景颜色、白色文本以及一些填充和边框来设置样式
示例
.button {
background-color: #8c8c8c;
color: white;
padding: 5px;
border: 1px solid black;
}
当我们将按钮放在具有更高特异性的另一个元素中时,按钮的外观有时会发生变化,并且属性会发生冲突。下面是一个例子
示例
.button {
background-color: #8c8c8c;
color: white;
padding: 5px;
border: 1px solid black;
}
#myDiv a {
color: red;
background-color: yellow;
}
为了“强制”所有按钮无论如何都具有相同的外观,我们可以将 !important
规则添加到按钮的属性中,如下所示
示例
.button {
background-color: #8c8c8c !important;
color: white !important;
padding: 5px !important;
border: 1px solid black !important;
}
#myDiv a {
color: red;
background-color: yellow;
}