CSS !important 规则

什么是 !important?

CSS 中的 !important 规则用于为属性/值增加比普通样式更高的优先级。

实际上,如果你使用了 !important 规则,它将覆盖该元素上该特定属性的所有先前样式规则!

让我们看一个例子:

Example

#myid {
  background-color: blue;
}
.myclass {
  background-color: gray;
}
p {
  background-color: red !important;
}

Try It Yourself

例子解释

在上面的例子中,所有三个段落都将获得红色背景颜色,尽管 ID 选择器和类选择器具有更高的特异性。!important 规则覆盖了这两种情况下的 background-color 属性。

关于 !important 的重要事项

覆盖 !important 规则的唯一方法是在源代码中包含另一个具有相同(或更高)特异性的声明中的 !important 规则 - 这就是问题的开始!这会使 CSS 代码变得混乱,调试也会变得困难,尤其是在你有大型样式表的情况下!

这里我们创建了一个简单的实例。当你查看 CSS 源代码时,并不十分清楚哪种颜色被认为是最重要的:

Example

#myid {
  background-color: blue !important;
}
.myclass {
  background-color: gray !important;
}
p {
  background-color: red !important;
}

Try It Yourself

提示:了解 !important 规则是好的。你可能会在一些 CSS 源代码中看到它。但是,除非你绝对必须使用它,否则不要使用它。

ອາດມີການນຳໃຊ້ !important ທີ່ມີຄວາມມີຫຼັກຫຼາຍສອງສາມຄັ້ງ:

ການນຳໃຊ້ອີກຢ່າງໜຶ່ງ: !important ການຕອບສະໜອງຂອງມັນຈະເປັນ:ຖ້າເຈົ້າຕ້ອງການປົກປິດກົນລະບຽບທີ່ບໍ່ສາມາດປົກປິດບາງກົນລະບຽບອີກນັ້ນ.ນັ້ນຈະຕາມທີ່ເຈົ້າກຳລັງນຳໃຊ້ລະບົບຄົ້ນຄວ້າສັນຍາລະບຽບ(CMS)ແລະບໍ່ສາມາດດັດແກ້ວິສະວະກອນ CSS.ບໍ່ມີການປົກປິດກົນລະບຽບພິເສດບາງຢ່າງທີ່ສາມາດປົກປິດກົນລະບຽບ CMS:

ການນຳໃຊ້ອີກຢ່າງໜຶ່ງ: !important ການຕອບສະໜອງຂອງມັນຈະເປັນ:ຖ້າເຈົ້າຕ້ອງການວ່ານັກວິດີໂອທັງໝົດຂອງເວັບໄຊຈະມີຮູບແບບພິເສດ.ບ່ອນນີ້ນັກວິດີໂອຈະມີຮູບແບບສີສີຂຽວສີທໍ້າທີ່ຫຼາຍກວ່າບາງການບັນທຶກຂອງການການປະກອບຂອງບາງທາງລະບຽບ:

Example

.button {
  background-color: #8c8c8c;
  color: white;
  padding: 5px;
  border: 1px solid black;
}

Try It Yourself

ຖ້າພວກເຮົາຕັດຕັ້ງນັກວິດີໂອໃນປະກອບທີ່ມີຄວາມສະເພາະສູງຫຼາຍກວ່າອີກໜຶ່ງຢ່າງໃດນັ້ນສະແດງຂອງນັກວິດີໂອຈະປ່ຽນແປງແລະຜົນຂອງທາງລະບຽບຈະມີການຂັດແຍ່ງ.ນັ້ນມັນຈະເປັນຫົວຂໍ້ນັ້ນ:

Example

.button {
  background-color: #8c8c8c;
  color: white;
  padding: 5px;
  border: 1px solid black;
}
#myDiv a {
  color: red;
  background-color: yellow;
}

Try It Yourself

To 'force' all buttons to have the same appearance at all times, we can use !important Add rules to the button's properties as shown below:

Example

.button {
  background-color: #8c8c8c !important;
  color: white !important;
  padding: 5px !important;
  border: 1px solid black !important;
}
#myDiv a {
  color: red;
  background-color: yellow;
}

Try It Yourself