# postcss-px-to-unit

> A postcss plugin to convert px to relative length units (vw / vh / rem)

Latest version **3.6.0** (published 2026-06-10) · MIT license · 0 weekly downloads

## Install

```sh
npm install postcss-px-to-unit
pnpm add postcss-px-to-unit
yarn add postcss-px-to-unit
bun add postcss-px-to-unit
```

## Health

**Score 60/100 (C)** — status: active.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 3.6.0 |
| Published | 2026-06-10 |
| First published | 2025-03-10 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | ^18.14.0 \|\| ^20.0.0 \|\| ^22.0.0 \|\| >=24.0.0 |
| Dependencies | 1 |
| Unpacked size | 19.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | SadWood |
| Maintainers | sadwood |
| Keywords | postcss, px2rem, px2vw, px2vh, rem, vh, viewport |

## Links

- npm: https://www.npmjs.com/package/postcss-px-to-unit
- Repository: https://github.com/SadWood/postcss-px-to-unit
- Homepage: https://github.com/SadWood/postcss-px-to-unit#readme
- Issues: https://github.com/SadWood/postcss-px-to-unit/issues
- npm.io page: https://npm.io/package/postcss-px-to-unit

## Dependencies (1)

- [postcss-value-parser](https://npm.io/package/postcss-value-parser.md) ^4.2.0

## Alternatives

- [@mdxeditor/editor](https://npm.io/package/@mdxeditor/editor.md) — 962.4K weekly downloads
- [mmdb-lib](https://npm.io/package/mmdb-lib.md) — 680.9K weekly downloads
- [playcanvas](https://npm.io/package/playcanvas.md) — 36.2K weekly downloads
- [@glw907/cairn-cms](https://npm.io/package/@glw907/cairn-cms.md) — 967 weekly downloads
- [markdown-to-confluence](https://npm.io/package/markdown-to-confluence.md) — 103 weekly downloads

## Recent versions

- 3.6.0 (latest) — 2026-06-10
- 3.5.1 — 2026-06-04
- 3.5.0 — 2026-06-04
- 3.4.0 — 2026-06-02
- 3.3.2 — 2025-03-12
- 3.3.1 — 2025-03-12
- 3.3.0 — 2025-03-12
- 3.2.0 — 2025-03-12
- 3.1.0 — 2025-03-12
- 3.0.0 — 2025-03-10

## README

# postcss-px-to-unit

An efficient PostCSS plugin for converting px units to relative length units (vw / vh / rem). This project has been refactored with performance optimizations, providing faster processing speed and more reliable conversion results.

## Install

```shell
# npm
npm install postcss-px-to-unit -D

# yarn
yarn add postcss-px-to-unit -D

# pnpm
pnpm add postcss-px-to-unit -D
```

## Usage

```javascript
// webpack.config.js
import PxToUnit from 'postcss-px-to-unit';

...
{
  loader: 'postcss-loader',
  plugins: [
    PxToUnit({
      // options
    })
  ]
}
...
```

```javascript
// vite.config.js
import PxToUnit from "postcss-px-to-unit";

export default defineConfig(() => ({
  // ...
  css: {
    postcss: {
      plugins: [
        PxToUnit({
          // options
        }),
      ],
    },
  },
  // ...
}));
```

## Options

```javascript
PxToUnit({
  targetUnit: "vw",
  ignoreThreshold: 1,
  viewportWidth: 375,
  viewportHeight: 667,
  htmlFontSize: 37.5,
  unitPrecision: 5,
  excludeFiles: [],
  excludeSelectors: [],
  excludeProperties: [],
  cacheSize: 100,
  debug: false,
});
```

| Option            | Default | Description                                                                                                                            |
| ----------------- | :-----: | :------------------------------------------------------------------------------------------------------------------------------------- |
| targetUnit        |  'vw'   | Target relative length unit. Support 'vw', 'vh', 'rem' and 'vw&rem'                                                                    |
| ignoreThreshold   |    1    | px values less than or equal to this threshold won't be converted (compared by absolute value, so `-10px` is treated as `10px`)        |
| viewportWidth     |   375   | Base viewport width (for targetUnit: 'vw')                                                                                             |
| viewportHeight    |   667   | Base viewport height (for targetUnit: 'vh')                                                                                            |
| htmlFontSize      |  37.5   | Base html font-size (for targetUnit: 'rem')                                                                                            |
| unitPrecision     |    5    | Unit value precision                                                                                                                   |
| excludeFiles      |   []    | Exclude file paths, supports regexp. (example: [/node_modules/])                                                                       |
| excludeSelectors  |   []    | Exclude CSS selectors and their nested subtree, supports string and regexp. (example: ['.ignore'])                                     |
| excludeProperties |   []    | Exclude CSS properties, supports string and regexp. (example: [/^width$/])                                                             |
| cacheSize         |   100   | Max number of cached conversion results (LRU). Use `Infinity` for an unbounded cache, or `0` / a non-positive value to disable caching |
| debug             |  false  | Print debug logs of skipped/converted values                                                                                           |

### Behavior notes

- **Token-level value parsing.** Values are parsed into tokens before conversion, so only real `px` dimensions are touched. `px` appearing inside strings, `url(...)`, or CSS variable names is left untouched — e.g. `width: var(--size-10px)` stays `var(--size-10px)`. Normal cases like `calc(100% - 10px)` are still converted.
- **Invalid numeric options fall back to defaults.** `viewportWidth` / `viewportHeight` / `htmlFontSize` must be positive finite numbers (otherwise they fall back to `375` / `667` / `37.5`). `unitPrecision` must be a non-negative finite integer (otherwise `5`) and is clamped to a maximum of `20` to avoid floating-point overflow. `ignoreThreshold` must be a non-negative finite number (otherwise `1`).
- **Excluded selectors skip nested CSS too.** When `excludeSelectors` matches a rule, declarations in its nested rule / at-rule subtree are left unchanged as well. For example, with `excludeSelectors: ['.skip']`, `.skip { .child { width: 10px } }` is not converted.
- **Unsupported `targetUnit`.** Only `'vw'`, `'vh'`, `'rem'`, and `'vw&rem'` are supported. Any other value (including a wrong case like `'VW'`) emits a single PostCSS warning and performs no conversion.
- **The `vw&rem` fallback combo only applies to `vw`/`rem`.** The `'vh'` mode emits a single `vh` declaration with no rem fallback.

### targetUnit: 'vh' mode

Use the 'vh' mode when a value should scale against the viewport height.

```css
/* Input */
.test {
  height: 66.7px;
}

/* Output */
.test {
  height: 10vh;
}
```

### targetUnit: 'vw&rem' mode

If you want to use vw units but are concerned about browser compatibility, you can use the 'vw&rem' mode. For example:

```css
/* Input */
.test {
  border: 3.75px solid #fff;
}

/* Output */
.test {
  border: 0.1rem solid #fff;
  border: 1vw solid #fff;
}
```

For browsers that don't support vw, it will automatically use rem for layout.

**Note: If you need to limit max/min width of the layout, this mode is not suitable for you**

### PX case sensitivity

The conversion process is case sensitive. You can use PX to avoid conversion in special cases.

```text
/* Input */
.test {
  padding: 3.75px 3.75PX;
}

/* Output */
.test {
  padding: 1vw 3.75PX;
}
```

## Performance Optimizations

Compared to the original version, this project includes the following optimizations:

- More efficient CSS parsing and processing logic
- Reduction of unnecessary calculations and conversion operations
- Optimized file processing workflow, improving processing speed for large projects

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details

---
_Source: https://npm.io/package/postcss-px-to-unit · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
