or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-postcss-minify-selectors

Minify selectors with PostCSS.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/postcss-minify-selectors@7.0.x

To install, run

npx @tessl/cli install tessl/npm-postcss-minify-selectors@7.0.0

index.mddocs/

PostCSS Minify Selectors

PostCSS Minify Selectors is a PostCSS plugin that optimizes CSS selectors by removing unnecessary parts, normalizing whitespace, and applying various minification rules. It helps reduce CSS bundle sizes by cleaning up selector syntax while maintaining functionality.

Package Information

  • Package Name: postcss-minify-selectors
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install postcss-minify-selectors

Core Imports

const postcssMinifySelectors = require("postcss-minify-selectors");

For ESM:

import postcssMinifySelectors from "postcss-minify-selectors";

Basic Usage

const postcss = require("postcss");
const postcssMinifySelectors = require("postcss-minify-selectors");

// Basic usage with default options
const result = await postcss([
  postcssMinifySelectors()
]).process(css, { from: undefined });

// With custom options
const result = await postcss([
  postcssMinifySelectors({ sort: false })
]).process(css, { from: undefined });

Input CSS:

h1 + p, h2, h3, h2{color:blue}
*#id, *.class, *[href]{background:red}
::before, ::after{content:""}
:nth-child(1), :nth-child(2n+1){font-weight:bold}
[   class=   "test"   ], [title="*.js"]{border:1px solid red}

Output CSS:

h1+p,h2,h3{color:blue}
#id,.class,[href]{background:red}
:before,:after{content:""}
:first-child,:nth-child(odd){font-weight:bold}
[class=test],[title="*.js"]{border:1px solid red}

Capabilities

Plugin Creator Function

Creates a PostCSS plugin instance with optional configuration.

/**
 * Creates a PostCSS plugin for minifying selectors
 * @param {Options} opts - Optional configuration object
 * @returns {Plugin} PostCSS plugin instance
 */
function postcssMinifySelectors(opts?: Options): Plugin;

Parameters:

  • opts (optional): Configuration options object

Returns:

  • PostCSS plugin object with postcssPlugin property and OnceExit method

Plugin Options

Configuration options for controlling selector minification behavior.

interface Options {
  /** Whether to sort selectors alphabetically (default: true) */
  sort?: boolean;
}

Properties:

  • sort (optional): Boolean flag to enable/disable selector sorting. Default: true

Plugin Properties

The plugin function includes PostCSS compatibility indicators.

/** Indicates PostCSS plugin compatibility */
postcssMinifySelectors.postcss: true;

Selector Optimizations

The plugin applies the following optimizations:

Universal Selector Removal

Removes qualified universal selectors where they are redundant:

  • *#id#id
  • *.class.class
  • *[href][href]
  • *:not(.green):not(.green)

Whitespace Normalization

Normalizes whitespace around selectors and combinators:

  • h1, h2, h3h1,h2,h3
  • h1 + ph1+p
  • h1 ph1 p

Attribute Selector Optimization

Optimizes attribute selectors by:

Quote removal and normalization:

  • Removing unnecessary quotes when safe: [class="woop_woop_woop"][class=woop_woop_woop]
  • Preserving quotes for complex values: [class*=" icon-"] (spaces), [data-attr~="key1=1"] (equals signs)
  • Preserving quotes for empty values: [title=""] and single hyphens: [title="-"]

Space and formatting normalization:

  • Trimming excess whitespace: [ color= "blue" ][color=blue]
  • Normalizing line breaks: [class="woop \\ woop woop"][class="woop woop woop"]
  • Operator spacing: removes spaces around =, ~=, |=, ^=, $=, *=

Case-insensitive flag handling:

  • Proper spacing: [color="blue" i ][color=blue i]
  • Preserves the case-insensitive flag with correct spacing

Attribute name trimming:

  • Normalizes attribute names: removes leading/trailing spaces

Pseudo-selector Optimization

Optimizes pseudo-selectors by:

nth-child/nth-of-type conversions:

  • Converting nth-child(1):first-child
  • Converting nth-last-child(1):last-child
  • Converting nth-of-type(1):first-of-type
  • Converting nth-last-of-type(1):last-of-type
  • Converting even2n in nth-child expressions
  • Converting 2n+1odd in nth-child expressions
  • Case insensitive: :NTH-CHILD(1):first-child
  • Space normalization: :nth-last-of-type(2n + 2):nth-last-of-type(2n+2)

Double-colon to single-colon conversion for backward compatibility:

  • ::before:before
  • ::after:after
  • ::first-letter:first-letter
  • ::first-line:first-line
  • Case preservation: ::BEFORE:BEFORE

:not() pseudo-class optimizations:

  • Whitespace trimming: :not(.article, .comments):not(.article,.comments)
  • Deduplication inside :not(): :not(h2, h3, h4, h5, h5, h6):not(h2,h3,h4,h5,h6)
  • Universal selector removal: :not( *[href="foo"] ):not([href=foo])

Keyframe Selector Optimization

Optimizes keyframe selectors:

  • from0%
  • 100%to (when used alone)
  • Case insensitive: FROM0%
  • Preserves complex keyframe selectors like entry 100% (won't convert to entry to)

Duplicate Removal

Removes duplicate selectors within the same rule.

Selector Sorting

When enabled (default), sorts selectors alphabetically for consistency.

Safety Features and Edge Cases

The plugin includes comprehensive safety measures to ensure optimizations don't break functionality:

String boundary preservation:

  • Never modifies content within quoted strings in attribute values
  • Preserves complex attribute values containing CSS selectors, keywords, or special characters
  • Handles both single and double quoted strings properly

Comment handling:

  • Maintains CSS comments while optimizing around them
  • Preserves the universal selector between comments: /*comment*/*/*comment*/

Framework compatibility:

  • Polymer mixins: Handles CSS custom property mixins like --my-toolbar-theme:{color:blue};
  • Escaped sequences: Preserves escaped zero plus sequences like .\\31 0\\+
  • Namespace selectors: Properly handles [foo|bar], [*|att], [|att]
  • Unicode characters: Preserves special characters like ½

Context-aware optimization:

  • Distinguishes between actual duplicates and similar-looking but semantically different selectors
  • Preserves meaningful universal selectors in specific contexts (combinators, etc.)
  • Smart handling of file glob patterns: [glob="/**/*.js"] (preserved)
  • Preserves qualified universals in attribute values: [class=" *.js "]

Mixin compatibility:

  • Skips selectors ending with : (likely custom mixins)
  • Compatible with other PostCSS plugins and their generated selectors

Usage Examples

Disable Sorting

const postcss = require("postcss");
const postcssMinifySelectors = require("postcss-minify-selectors");

const result = await postcss([
  postcssMinifySelectors({ sort: false })
]).process(css, { from: undefined });

Integration with PostCSS Config

// postcss.config.js
module.exports = {
  plugins: [
    require("postcss-minify-selectors")({
      sort: true
    })
  ]
};

Use with cssnano

This plugin is part of the cssnano preset but can be used independently:

const postcss = require("postcss");
const postcssMinifySelectors = require("postcss-minify-selectors");

const result = await postcss([
  postcssMinifySelectors(),
  // other plugins...
]).process(css, { from: undefined });

Types

interface Options {
  /** Whether to sort selectors alphabetically (default: true) */
  sort?: boolean;
}

interface Plugin {
  /** PostCSS plugin identifier */
  postcssPlugin: string;
  /** Main processing method called once after all rules are processed */
  OnceExit(css: Root): void;
}

interface Root {
  /** Walk through all rules in the CSS */
  walkRules(callback: (rule: Rule) => void): void;
}

interface Rule {
  /** The selector string */
  selector: string;
  /** Raw selector information */
  raws: {
    selector?: {
      value: string;
      raw: string;
    };
  };
}

Dependencies

The plugin relies on these external packages:

  • postcss-selector-parser: For parsing and manipulating CSS selectors
  • cssesc: For CSS string escaping utilities