@bramus/specificity

中文文档
2.4.3发布于 2026/10/06MITTypeScriptESM + CJS近 30 天下载 1.9亿

Calculate specificity of a CSS Selector

原始使用文档
文档目录10 节
  1. Installation
  2. Usage / Example
  3. The Return Format
  4. Utility Functions (Static Methods)
  5. Utility Functions (Standalone)
  6. Type Definitions
  7. Binary/CLI
  8. Benchmark
  9. License
  10. Acknowledgements

Calculate CSS Specificity

Specificity

@bramus/specificity is a package to calculate the specificity of CSS Selectors. It also includes some convenience functions to compare, sort, and filter an array of specificity values.

Supports Selectors Level 4, including those special cases :is(), :where(), :not(), etc.

Demo: https://codepen.io/bramus/pen/WNXyoYm

Installation

npm i @bramus/specificity

Usage / Example

At its core, @bramus/specificity exposes a Specificity class. Its static calculate method can be used to calculate the specificity of a given CSS Selector List string.

import Specificity from '@bramus/specificity';

const specificities = Specificity.calculate('header:where(#top) nav li:nth-child(2n), #doormat');

Because calculate accepts a Selector List — which can contain more than 1 Selector — it will always return an array, with each entry being a Specificity instance — one per found selector.

const specificities = Specificity.calculate('header:where(#top) nav li:nth-child(2n), #doormat');
specificities.map((s) => s.toString()); // ~> ["(0,1,3)","(1,0,0)"]

💡 If you know you’re passing only a single Selector into calculate(), you can use JavaScript’s built-in destructuring to keep your variable names clean.

const [s] = Specificity.calculate('header:where(#top) nav li:nth-child(2n)');
s.toString(); // ~> "(0,1,3)"

💡 Under the hood, @bramus/specificity uses CSSTree to do the parsing of strings to Selectors. As a result, the calculate method also accepts a CSSTree AST of the types Selector and SelectorList.

If you have a pre-parsed CSSTree AST of the type Selector you can pass it into Specificity.calculateForAST(). It performs slightly better than Specificity.calculate() as it needs to check fewer things. It differs from Specificity.calculate() in that it does not return an array of Specificity instances but only a single value.

The Return Format

A calculated specificity is represented as an instance of the Specificity class. The Specificity class includes methods to get the specificity value in a certain format, along with some convenience methods to compare it against other instances.

// 🚀 Thunderbirds are go!
import Specificity from '@bramus/specificity';

// ✨ Calculate specificity for each Selector in the given Selector List
const specificities = Specificity.calculate('header:where(#top) nav li:nth-child(2n), #doormat');

// 🚚 The values in the array are instances of the Specificity class
const s = specificities[0]; // Instance of Specificity

// 👀 Read the specificity value using one of its accessors
s.value; // { a: 0, b: 1, c: 3 }
s.a; // 0
s.b; // 1
s.c; // 3

// 🛠 Convert the calculated value to various formats using one of the toXXX() instance methods
s.toString(); // "(0,1,3)"
s.toArray(); // [0, 1, 3]
s.toObject(); // { a: 0, b: 1, c: 3 }

// 💡 Extract the matched selector string
s.selectorString(); // "header:where(#top) nav li:nth-child(2n)"

// 🔀 Use one of its instance comparison methods to compare it to another Specificity instance
s.isEqualTo(specificities[1]); // false
s.isGreaterThan(specificities[1]); // false
s.isLessThan(specificities[1]); // true

// 💻 Don’t worry about JSON.stringify()
JSON.stringify(s);
// {
//    "selector": 'header:where(#top) nav li:nth-child(2n)',
//    "asObject": { "a": 0, "b": 1, "c": 3 },
//    "asArray": [0, 1, 3],
//    "asString": "(0,1,3)",
// }

Utility Functions (Static Methods)

This package also exposes some utility functions to work with specificities. These utility functions are all exposed as static methods on the Specificity class.

  • Comparing:

    • Specificity.compare(s1, s2): Compares s1 to s2. Returns a value that can be:
      • > 0 = Sort s2 before s1 (i.e. s1 is more specific than s2)
      • 0 = Keep original order of s1 and s2 (i.e. s1 and s2 are equally specific)
      • < 0 = Sort s1 before s2 (i.e. s1 is less specific than s2)
    • Specificity.equals(s1, s2): Returns true if s1 and s2 have the same specificity. If not, false is returned.
    • Specificity.greaterThan(s1, s2): Returns true if s1 has a higher specificity than s2. If not, false is returned.
    • Specificity.lessThan(s1, s2): Returns true if s1 has a lower specificity than s2. If not, false is returned.
  • Sorting:

    • Specificity.sortAsc(s1, s2, …, sN): Sorts the given specificities in ascending order (low specificity to high specificity)
    • Specificity.sortDesc(s1, s2, …, sN): Sorts the given specificities in descending order (high specificity to low specificity)
  • Filtering:

    • Specificity.min(s1, s2, …, sN): Filters out the value with the lowest specificity
    • Specificity.max(s1, s2, …, sN): Filters out the value with the highest specificity

A specificity passed into any of these utility functions can be any of:

  • An instance of the included Specificity class
  • A simple Object such as {'a': 1, 'b': 0, 'c': 2}

Utility Functions (Standalone)

All static methods the Specificity class exposes are also exported as standalone functions using Subpath Exports.

If you're only interested in including some of these functions into your project you can import them from their Subpath. As a result, your bundle size will be reduced greatly (except for including the standalone calculate, as it returns an array of Specificity instances that relies on the whole lot)

import { calculate, calculateForAST } from '@bramus/specificity/core';
import { compare, equals, greaterThan, lessThan } from '@bramus/specificity/compare';
import { min, max } from '@bramus/specificity/filter';
import { sortAsc, sortDesc } from '@bramus/specificity/sort';

Type Definitions

Although @bramus/specificity is written in Vanilla JavaScript, it does include Type Definitions which are exposed via its package.json.

Binary/CLI

@bramus/specificity exposes a binary named specificity to calculate the specificity of a given selector list on the CLI. For each selector that it finds, it'll print out the calculated specificity as a string on a new line.

$ specificity "header:where(#top) nav li:nth-child(2n), #doormat"
(0,1,3)
(1,0,0)

Benchmark

A benchmark is included, which you can invoke using npm run benchmark.

Sample results (tested on a MacBook Air M3):

Specificity.calculate(string) x 420,682 ops/sec ±0.34% (98 runs sampled)
Specificity.calculate(ast) - using SelectorList x 8,994,080 ops/sec ±0.25% (98 runs sampled)
Specificity.calculate(ast) - using Selector x 11,054,856 ops/sec ±0.39% (91 runs sampled)
Specificity.calculateForAST(ast) x 12,652,322 ops/sec ±0.35% (96 runs sampled)

License

@bramus/specificity is released under the MIT public license. See the enclosed LICENSE for details.

Acknowledgements

The idea to create this package was sparked by the wonderful Specificity Calculator created by Kilian Valkhof / Polypane, a highly educational tool that not only calculates the specificity, but also explains which parts are responsible for it.

The heavy lifting of doing the actual parsing of Selectors is done by CSSTree.

版本与发布记录

@bramus/specificity 共发布 26 个版本,首次发布于 2022/02/23;过去 12 个月发布了 1 个版本。

版本发布日期距今
2.4.3latest2026/10/061 个月前
2.4.22025/06/031.4 年前
2.4.12025/02/191.7 年前
2.4.02025/02/191.7 年前
2.3.02023/04/083 年前
2.2.02022/12/153 年前

其他发布通道:next → 2.0.0-beta.11。

关于 @bramus/specificity 的常见问题

@bramus/specificity 是什么?

Calculate specificity of a CSS Selector

如何安装 @bramus/specificity?

在项目目录运行 npm install @bramus/specificity,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 specificity,可以用 npx specificity 直接运行。

@bramus/specificity 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bramus/specificity 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@bramus/specificity 可以商用吗?

@bramus/specificity 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bramus/specificity 的下载量有多少?

根据 npm 官方下载统计,@bramus/specificity 在 2026/10/09 – 2026/11/07 这 30 天内被下载 191,698,498 次,日均约 6,389,950 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bramus/specificity 还在维护吗?

最新版本 2.4.3 发布于 2026/10/06(1 个月前);至今共发布 26 个版本,其中过去 12 个月发布了 1 个;首次发布于 2022/02/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。