在 CSS 中使用“!important”會有什麼含義?


!important 規則會覆蓋所有先前的樣式規則。它基於優先順序或特異性的概念。!important 規則提供了一種讓 CSS 級聯的方式。它還包含始終要應用的規則。無論該規則在 CSS 文件中出現的位置,擁有!important 屬性的規則都將始終被應用。讓我們看一個例子 -

優先順序 - 不使用!important

示例

讓我們首先看一個不使用!important 時特異性和優先順序如何工作的示例 -

<!DOCTYPE html>
<html>
<head>
   <style>
      .mycolor{
         color: red;
      }
         .mycolor{
         color: orange;
      }         
   </style>
</head>
<body>
   <h1>Checking Priority</h1>
   <div class='mycolor'>
   This is orange colored
   </div>
</body>
</html>

輸出

優先順序 - 使用!important

示例

現在,我們將看一個使用!important 時特異性和優先順序如何工作的示例 -

<!DOCTYPE html>
<html>
<head>
   <style>
      .mycolor{
         color: red !important;
      }
         .mycolor{
         color: orange;
      }         
   </style>
</head>
<body>
   <h1>Checking Priority</h1>
   <div class='mycolor'>
   This is red colored because we used !important to override
   </div>
</body>
</html>

輸出

更新日期: 2022 年 12 月 6 日

121 次瀏覽

開啟你的職業

完成課程獲得認證

開始
廣告
© . All rights reserved.