specificity

Calculate the specificity of a CSS selector

MIT 16 个版本
安装
npm install specificity
yarn add specificity
pnpm add specificity
bun add specificity
README

Specificity Calculator

A JavaScript module for calculating and comparing the specificity of CSS selectors. The module is used on the Specificity Calculator website.

Note that version 1 is a complete re-write with support for CSS Selectors Level 4, and has a different API than earlier versions.

calculate(selector)

Parameters

  • selector: string - should be a valid CSS selector

Returns

A Specificity object with a type of Record<"A" | "B" | "C", number>.

Examples

calculate("#id");
{
  A: 1,
  B: 0,
  C: 0
}

calculate(".classname");
{
  A: 0,
  B: 1,
  C: 0
}

calculate("element");
{
  A: 0,
  B: 0,
  C: 1
}

calculate('ul#nav li.active a');
{
  A: 1,
  B: 1,
  C: 3
}

compare(a, b)

Parameters

  • a: Specificity object with a type of Record<"A" | "B" | "C", number>
  • b: Specificity object with a type of Record<"A" | "B" | "C", number>

Returns

Returns a positive number if a has a higher specificity than b Returns a negative number if a has a lower specificity than b Returns 0 if a has the same specificity than b

Examples

[
  "element",
  ".classname",
  "#id",
]
  .map(calculate)
  .sort(compare);

[ { A: 0, B: 0, C: 1 }, { A: 0, B: 1, C: 0 }, { A: 1, B: 0, C: 0 } ]

compareDesc(a, b)

Same as compare but returns the opposite value, for use in sorting specificity objects with the highest specificity first.

版本列表
1.0.0-beta 2023-06-23
1.0.0 2023-06-23
0.4.1 2018-08-28
0.4.0 2018-07-17
0.3.2 2017-09-26
0.3.1 2017-06-30
0.3.0 2016-10-05
0.2.1 2016-06-20
0.2.0 2016-06-19
0.1.6 2016-06-19
0.1.5 2016-01-06
0.1.4 2014-04-14
0.1.3 2012-09-23
0.1.2 2012-09-02
0.1.1 2012-08-20
0.1.0 2012-08-20