- The HTML and CSS Workshop
- Lewis Coulson Brett Jephson Rob Larsen Matt Park Marian Zburlea
- 322字
- 2021-06-11 12:54:57
CSS Specificity
If we have two CSS declarations that have an effect on the same style property of an element, how do we know which of those declarations will take precedent?
There are several factors that decide the ranking of a CSS declaration and whether it is the style the browser will apply. The term for these factors is specificity.
A style attribute that adds inline styles to an element has the highest specificity value. An ID selector has a greater specificity value than a class selector and a class selector or attribute selector has a greater specificity value than an element type. We can calculate the specificity value by giving points to each of these specificity values.
The most common way of representing this is as a comma-separated list of integers, where the leftmost integer represents the highest specificity. In other words, the leftmost value is the inline style attribute; next is an ID selector; next is a class selector, pseudo-class, or attribute selector; and the rightmost value is an element.
An inline style would have the value 1, 0, 0, 0. An ID selector would have the value 0, 1, 0, 0. A class selector would have the value 0, 0, 1, 0, and an h1 element selector would have the value 0, 0, 0, 1.
Let's look at a few examples with more complex selectors:
- li.selected a[href] has two element selectors (li and a), a class selector (.selected) and an attribute selector ([href]), so its specificity value would be 0, 0, 2, 2:

Figure 1.30: Calculating the specificity of li.selected a[href]
- #newItem #mainHeading span.smallPrint has two ID selectors, a class selector (.smallPrint), and a span element, so its specificity value would be 0, 2, 1, 1:

Figure 1.31: Calculating the specificity of #newItem #mainHeading span.smallPrint
Comparing the two selectors, we can see that the selector in the second example is more specific than the selector in the first example.
- Android Studio Essentials
- 深入淺出Prometheus:原理、應(yīng)用、源碼與拓展詳解
- AngularJS深度剖析與最佳實踐
- Getting Started with SQL Server 2012 Cube Development
- QGIS:Becoming a GIS Power User
- Mathematica Data Analysis
- Visual FoxPro程序設(shè)計習(xí)題集及實驗指導(dǎo)(第四版)
- 零基礎(chǔ)學(xué)C語言第2版
- Vue.js 3應(yīng)用開發(fā)與核心源碼解析
- RESTful Web Clients:基于超媒體的可復(fù)用客戶端
- 多媒體技術(shù)及應(yīng)用
- Maven for Eclipse
- Python預(yù)測分析與機器學(xué)習(xí)
- 實戰(zhàn)Python網(wǎng)絡(luò)爬蟲
- Python機器學(xué)習(xí)開發(fā)實戰(zhàn)