CSS中選擇器優先級與!important權重使用


CSS中的選擇器優先級與!important權重使用

  • .class選擇器要高於標簽選擇器。
  • #id選擇器要高於.class選擇器。
  • 標簽選擇器是優先級最低的選擇器。
  • !important的屬性它的權重值優先級最高的,大於所有的選擇器。

標簽選擇器和.class選擇器

  • 讓我們進入標簽選擇器和.class選擇器誰的優先級高實踐,實踐內容如:將HTML頁面中的h2標簽設置文本顏色。
  • 代碼塊

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>優先級</title>
    <style>
        h2{
           color: red; /*紅色*/
       }
       .box{
            color: springgreen; /*綠色*/
       }
    </style>
</head>
  
<body>
    <h2 class="box">微笑是最初的信仰</h2>
</body>
</html>
  • 結果圖

.class選擇器和id選擇器

  • 讓我們進入.class選擇器和id選擇器誰的優先級高實踐,實踐內容如:將HTML頁面中的h2標簽設置文本顏色。
  • 代碼塊

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>優先級</title>
    <style>
       h2{
           color: red; /*紅色*/
       }
       .box{
            color: springgreen; /*綠色*/
       }
       #box{
           color:blue; /*藍色*/
       }
    </style>
</head>
  
<body>
   <h2 class="box" id="box">微笑是最初的信仰</h2>
</body>
</html>
  • 結果圖

!important權重使用

  • 現在我們知道了標簽選擇器優先級最低,那么筆者將標簽選擇器添加!important屬性呢,誰的優先級更高呢?
  • !important權重使用格式如下:
    color: red !important; /*紅色*/
  • 注意:屬性:值 !important屬性值用空格隔開即可。

  • 讓我們進入 !important屬性使用實踐,看看!important屬性威力有多大哈。
  • 代碼塊

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>!important使用</title>
    <style>
       h2{
           color: red !important; /*紅色*/
       }
       .box{
            color: springgreen; /*綠色*/
       }
       #box{
           color:blue; /*藍色*/
       }
    </style>
</head>
  
<body>
   <h2 class="box" id="box">微笑是最初的信仰</h2>
</body>
</html>
  • 結果圖

總結

  • 優先級從低到高如:標簽選擇器、.class選擇器、#id選擇器、!important屬性


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM