# CSS 10. CSS Specificity / CSS 的特定度 ### 我們為什麼需要了解 CSS Specificity 的觀念: - 假設來講,我們有一個 HTML 範例如下: ``` <h1>1234</h1> <p>Lorem ipsum dolor sit amet.</p> <h1>1234</h1> <p>Lorem ipsum dolor sit amet.</p> <h1>1234</h1> <p>Lorem ipsum dolor sit amet.</p> <h1>1234</h1> <p>Lorem ipsum dolor sit amet.</p> ``` - 於是我們來開始嘗試撰寫 CSS: 1. 先將 h1 變成 blue ``` h1 { color: blue; } ``` 2. 假設所有的 h1 都已經變成了藍色,那麼我接著再寫一個 h1 變成 red 呢?  - 這是一個很有意思的現象,當我在同個CSS 檔案下一行撰寫新的代碼 它會取代原本所寫好的屬性,這就是 CSS 階層式的觀念。 3. 若加上 class 或 id 就不會直接被後來寫進去的屬性給覆蓋掉 ``` <h1>1234</h1> <p>Lorem ipsum dolor sit amet.</p> <h1>1234</h1> <p>Lorem ipsum dolor sit amet.</p> <h1 class="greenText">1234</h1> <p>Lorem ipsum dolor sit amet.</p> <h1 class="blueText">1234</h1> <p>Lorem ipsum dolor sit amet.</p> ``` ``` h1.greenText { color: green; } .blueText { color: blue; } h1 { color: red; } ```  --- ### CSS 的規則: 1. 如果說,一般新寫入的 CSS 會覆蓋掉舊的屬性,是 CSS 的規則1. 那麼接下來學習的特定度將會是 CSS 的規則2. 2. CSS Specificity 表格: ``` 1. id - specificity(1,0,0) 2. class - specificity(0,1,0) 3. tags - specificity(0,0,1) ``` - 這邊可以做一個範例: 假設有一個 class 為 `h1.redText`,來做特定度拆解 h1 為 (0,0,1) 、 redText 為 (0,1,0) 那麼這個組合會變成什麼呢? >> (0,1,1) 所以,其實特定度的計算方式還算滿容易的,相當好辨識! 當特定度越高,越不能夠被後面寫的 CSS 所覆蓋著。 ###### tags: `2022 網頁開發全攻略教程 / CSS篇章`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up