A PostCSS plugin that converts px units to rem units for responsive design.
npx @tessl/cli install tessl/npm-postcss-pxtorem@6.1.00
# PostCSS PxToRem
1
2
PostCSS PxToRem is a PostCSS plugin that converts pixel (px) units to rem units in CSS stylesheets. It enables responsive design by allowing browsers to scale based on user font size preferences, while providing comprehensive configuration options for selective conversion.
3
4
## Package Information
5
6
- **Package Name**: postcss-pxtorem
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install postcss postcss-pxtorem --save-dev`
10
11
## Core Imports
12
13
```javascript
14
const pxtorem = require('postcss-pxtorem');
15
```
16
17
For ES modules:
18
19
```javascript
20
import pxtorem from 'postcss-pxtorem';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const postcss = require('postcss');
27
const pxtorem = require('postcss-pxtorem');
28
29
// Basic usage with default options
30
const result = postcss()
31
.use(pxtorem())
32
.process(css)
33
.css;
34
35
// With custom options
36
const result = postcss()
37
.use(pxtorem({
38
rootValue: 16,
39
propList: ['*'],
40
replace: true
41
}))
42
.process(css)
43
.css;
44
```
45
46
## Architecture
47
48
PostCSS PxToRem follows the standard PostCSS plugin architecture with three main processing hooks:
49
50
- **Once Hook**: Initializes plugin for each CSS file, determining file exclusion status and creating the pixel replacement function based on configuration
51
- **Declaration Hook**: Processes each CSS property declaration, applying px-to-rem conversion based on property matching rules and selector blacklists
52
- **AtRule Hook**: Handles CSS at-rules like `@media` queries when `mediaQuery` option is enabled
53
54
### Internal Utilities
55
56
The plugin uses several internal utility modules from the `lib/` directory:
57
58
- **pixel-unit-regex.js**: Creates regex patterns for matching pixel units while excluding values in quotes, `url()`, and `var()` functions
59
- **filter-prop-list.js**: Provides property list filtering with support for wildcards, exact matches, and exclusion patterns (using `!` prefix)
60
- **type.js**: Type checking utilities for validating configuration options (isString, isFunction, etc.)
61
62
### Processing Pipeline
63
64
1. **Initialization**: Plugin validates options, converts legacy option names, and prepares matching functions
65
2. **File Processing**: Each CSS file is checked against exclusion rules to determine if processing should occur
66
3. **Declaration Processing**: Property declarations are filtered by `propList` patterns and selector blacklists before conversion
67
4. **Value Replacement**: Pixel values are converted to rem units using the specified root value and precision settings
68
69
## Capabilities
70
71
### Plugin Factory Function
72
73
Creates a PostCSS plugin instance with the specified configuration options.
74
75
```javascript { .api }
76
/**
77
* Creates a PostCSS plugin for converting px to rem units
78
* @param {Object} options - Configuration options for the plugin
79
* @returns {Object} PostCSS plugin object
80
*/
81
function pxtorem(options = {});
82
```
83
84
### Configuration Options
85
86
The plugin accepts a comprehensive set of configuration options to control conversion behavior.
87
88
```javascript { .api }
89
interface PxToRemOptions {
90
/** Root element font size or function returning root size */
91
rootValue?: number | ((input: PostCSSInput) => number);
92
/** Decimal precision for rem units */
93
unitPrecision?: number;
94
/** Properties to convert from px to rem */
95
propList?: string[];
96
/** Selectors to ignore during conversion */
97
selectorBlackList?: (string | RegExp)[];
98
/** Replace px values instead of adding fallbacks */
99
replace?: boolean;
100
/** Convert px in media queries */
101
mediaQuery?: boolean;
102
/** Minimum pixel value to convert */
103
minPixelValue?: number;
104
/** File exclusion pattern */
105
exclude?: string | RegExp | ((filePath: string) => boolean);
106
/** Unit to convert from (default: "px") */
107
unit?: string;
108
}
109
```
110
111
### Default Options
112
113
The plugin uses the following default configuration:
114
115
```javascript { .api }
116
const defaultOptions = {
117
rootValue: 16,
118
unitPrecision: 5,
119
selectorBlackList: [],
120
propList: ['font', 'font-size', 'line-height', 'letter-spacing', 'word-spacing'],
121
replace: true,
122
mediaQuery: false,
123
minPixelValue: 0,
124
exclude: null,
125
unit: 'px'
126
};
127
```
128
129
### Property List Patterns
130
131
The `propList` option supports various matching patterns for selective property conversion:
132
133
```javascript { .api }
134
// Property list pattern examples
135
const propListPatterns = {
136
/** Exact property names */
137
exact: ['font-size', 'margin', 'padding'],
138
/** All properties */
139
all: ['*'],
140
/** Properties containing substring */
141
contains: ['*position*'], // matches background-position-x, etc.
142
/** Properties starting with prefix */
143
startsWith: ['font*'], // matches font-size, font-weight, etc.
144
/** Properties ending with suffix */
145
endsWith: ['*-spacing'], // matches letter-spacing, word-spacing, etc.
146
/** Negated patterns (exclude from conversion) */
147
exclude: ['*', '!border*'], // all properties except those starting with 'border'
148
};
149
```
150
151
## Usage Examples
152
153
### Basic Font Size Conversion
154
155
```css
156
/* Input CSS */
157
h1 {
158
margin: 0 0 20px;
159
font-size: 32px;
160
line-height: 1.2;
161
letter-spacing: 1px;
162
}
163
164
/* Output CSS (with default options) */
165
h1 {
166
margin: 0 0 20px;
167
font-size: 2rem;
168
line-height: 1.2;
169
letter-spacing: 0.0625rem;
170
}
171
```
172
173
### Convert All Properties
174
175
```javascript
176
const postcss = require('postcss');
177
const pxtorem = require('postcss-pxtorem');
178
179
const result = postcss()
180
.use(pxtorem({
181
propList: ['*'], // Convert all properties
182
replace: false // Keep px as fallback
183
}))
184
.process(css)
185
.css;
186
```
187
188
```css
189
/* Input */
190
.element {
191
width: 320px;
192
margin: 10px 20px;
193
border: 1px solid #ccc;
194
}
195
196
/* Output */
197
.element {
198
width: 320px;
199
width: 20rem;
200
margin: 10px 20px;
201
margin: 0.625rem 1.25rem;
202
border: 1px solid #ccc;
203
border: 0.0625rem solid #ccc;
204
}
205
```
206
207
### Selective Conversion with Exclusions
208
209
```javascript
210
const options = {
211
propList: ['*', '!border*', '!outline*'],
212
selectorBlackList: ['.ignore', /^\.mobile-/],
213
minPixelValue: 2
214
};
215
216
const result = postcss()
217
.use(pxtorem(options))
218
.process(css)
219
.css;
220
```
221
222
### Dynamic Root Value
223
224
```javascript
225
const options = {
226
rootValue: (input) => {
227
// Different root values based on file path
228
if (input.file.includes('mobile')) {
229
return 14;
230
}
231
return 16;
232
}
233
};
234
```
235
236
### File Exclusion
237
238
```javascript
239
const options = {
240
exclude: /node_modules/i, // Exclude node_modules files
241
// or function-based exclusion
242
exclude: (file) => file.includes('vendor')
243
};
244
```
245
246
### Media Query Conversion
247
248
```javascript
249
const options = {
250
mediaQuery: true // Enable px to rem conversion in media queries
251
};
252
253
const result = postcss()
254
.use(pxtorem(options))
255
.process(css)
256
.css;
257
```
258
259
```css
260
/* Input */
261
@media (min-width: 768px) {
262
.container {
263
max-width: 1200px;
264
}
265
}
266
267
/* Output */
268
@media (min-width: 48rem) {
269
.container {
270
max-width: 75rem;
271
}
272
}
273
```
274
275
## Types
276
277
### PostCSS Plugin Object
278
279
```javascript { .api }
280
interface PostCSSPlugin {
281
/** Plugin identifier */
282
postcssPlugin: 'postcss-pxtorem';
283
/** Initialize plugin for each CSS file */
284
Once(css: PostCSSRoot): void;
285
/** Process each CSS declaration */
286
Declaration(decl: PostCSSDeclaration): void;
287
/** Process CSS at-rules (like @media) */
288
AtRule(atRule: PostCSSAtRule): void;
289
}
290
```
291
292
### PostCSS Input
293
294
```javascript { .api }
295
interface PostCSSInput {
296
/** File path of the CSS being processed */
297
file: string;
298
/** CSS source content */
299
css: string;
300
}
301
```
302
303
## Advanced Configuration
304
305
### Case-Sensitive Unit Conversion
306
307
By default, only lowercase 'px' units are converted. Uppercase variants ('Px', 'PX') are ignored:
308
309
```css
310
/* This allows selective ignoring within the same file */
311
.convert {
312
font-size: 16px; /* converted to 1rem */
313
}
314
315
.ignore {
316
border: 1Px solid; /* ignored - keeps Px */
317
border-width: 2PX; /* ignored - keeps PX */
318
}
319
```
320
321
### Integration with Build Tools
322
323
```javascript
324
// Gulp integration
325
const gulp = require('gulp');
326
const postcss = require('gulp-postcss');
327
const pxtorem = require('postcss-pxtorem');
328
329
gulp.task('css', () => {
330
return gulp.src('src/**/*.css')
331
.pipe(postcss([
332
pxtorem({
333
replace: false
334
})
335
]))
336
.pipe(gulp.dest('dist'));
337
});
338
339
// Webpack integration (postcss.config.js)
340
module.exports = {
341
plugins: [
342
require('postcss-pxtorem')({
343
rootValue: 16,
344
propList: ['*']
345
})
346
]
347
};
348
```
349
350
## Plugin Compatibility
351
352
This plugin follows PostCSS plugin conventions and includes the required compatibility flag:
353
354
```javascript { .api }
355
// Plugin compatibility marker
356
pxtorem.postcss = true;
357
```