shou2017.com
JP

CSS Application Priority

Fri May 17, 2019
Sat Aug 10, 2024

The priority of CSS application is determined by the specificity of selectors.

Selector Specificity

When selectors have different levels of specificity

When CSS elements conflict, they are applied in order of higher CSS specificity.

CSS specificity, from highest:

  1. HTML style attribute (style="") inline
  2. ID (#sample)
  3. Class (.sample)
    • Pseudo-class (:hover)
    • Attribute ([type]=“submit”)
  4. Element type (div), pseudo-element (::before)
<div class="sample">sample text</div>
.sample { color: red; }  This one is applied
div { color: blue; } 

When selector specificity is equal

When competing styles have the same specificity, the one written later takes precedence.

<div class="red blue">sample text</div>

CSS side:

.blue { color: blue; }
.red { color: red; }  This one written later is applied

Note that it’s the order of CSS definition that matters, not the order of classes in the HTML.

When selector specificity spans multiple types

When multiple specifications overlap, specificity increases. When there are multiple selectors, they are calculated by addition.

Specificity calculation method

Example 1:

HTML side:

<div class="red blue">sample text</div>

CSS side:

div.blue { color: blue; } 0-0-1 + 0-1-0 = 0-1-1  This one is applied
.red { color: red; }      0-1-0 

Example 2:

HTML side:

<div class="about" id="about">
</div>

CSS side:

0-0-1 + 0-1-0 = 0-1-1
div.about {
    background-color: black;
}
0-0-1 + 1-0-0 = 1-0-1  This one is applied
div#about {
    background-color: red;
} 

HTML5/CSS3モダンコーディング フロントエンドエンジニアが教える3つの本格レイアウト スタンダード・グリッド・シングルページレイアウトの作り方

Tags
CSS