探索 CSS 中的 !important
规则
在这一步中,你将学习 CSS 中的 !important
规则,这是一种强大的方式,可以覆盖所有其他样式规则。虽然应谨慎使用,但在特定情况下它可能会很有帮助。
在 WebIDE 中打开上一步中的 index.html
文件。更新 HTML 以演示 !important
规则:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>CSS !important Rule</title>
<style>
/* We'll demonstrate the !important rule here */
</style>
</head>
<body>
<div id="important-demo" class="highlight">
<p>Understanding the !important CSS Rule</p>
</div>
</body>
</html>
现在,添加 CSS 以展示 !important
规则如何覆盖其他选择器:
/* Normal tag selector */
p {
color: green;
font-size: 16px;
}
/* Class selector */
.highlight {
color: blue;
border: 2px solid gray;
}
/* ID selector */
#important-demo {
color: red;
}
/* !important rule (highest priority) */
p {
color: purple !important;
font-weight: bold !important;
}
关于 !important
规则的关键点:
- 它覆盖所有其他选择器的优先级
- 应非常谨慎地使用,仅在绝对必要时使用
- 如果过度使用,可能会使 CSS 更难维护
当你保存并在浏览器中打开此文件时,你将看到:
- 段落文本将显示为紫色并加粗
!important
规则优先于其他选择器
浏览器中的示例输出:
- 段落文本为紫色、加粗
- 展示了
!important
如何覆盖其他样式规则