3 * [`postcss` function](#postcss-function)
4 * [`Processor` class](#processor-class)
5 * [`LazyResult` class](#lazyresult-class)
6 * [`Result` class](#result-class)
7 * [`Warning` class](#warning-class)
8 * [`CssSyntaxError` class](#csssyntaxerror-class)
9 * [Vendor module](#vendor-module)
10 * [List module](#list-module)
11 * [`Input` class](#input-class)
12 * [Nodes common methods](#nodes-common-methods)
13 * [Containers common methods](#containers-common-methods)
14 * [`Root` node](#root-node)
15 * [`AtRule` node](#atrule-node)
16 * [`Rule` node](#rule-node)
17 * [`Declaration` node](#declaration-node)
18 * [`Comment` node](#comment-node)
22 The `postcss` function is the main entry point for PostCSS.
25 var postcss = require('postcss');
28 For those using [TypeScript], typings are already provided in this package.
29 Simply, import PostCSS as you would normally.
32 import * as postcss from 'postcss';
35 [TypeScript]: http://www.typescriptlang.org/
37 ### `postcss(plugins)`
39 Returns a new [`Processor`] instance that will apply `plugins`
43 postcss([autoprefixer, cssnext, cssgrace]).process(css).css;
48 * `plugins (array)`: list of PostCSS plugins to be included as processors.
50 Plugins can also be included with the [`Processor#use`] method.
51 See its description below for details about plugin formats.
53 ### `postcss.parse(css, opts)`
55 Parses source `css` and returns a new `Root` node, which contains
59 // Simple CSS concatenation with source map support
60 var root1 = postcss.parse(css1, { from: file1 });
61 var root2 = postcss.parse(css2, { from: file2 });
62 root1.append(root2).toResult().css;
67 * `css (string|#toString)`: String with input CSS or any object
68 with `toString()` method, like a Buffer.
69 * `opts (object) optional`: options:
70 * `from`: the path to the source CSS file. You should always set `from`,
71 because it is used in map generation and in syntax error messages.
72 * `map`: an object of [source map options].
73 Only `map.prev` is used in `parse`.
75 ### `postcss.plugin(name, initializer)`
77 Creates a PostCSS plugin with a standard API.
80 var remove = postcss.plugin('postcss-remove', function (opts) {
82 var filter = opts.prop || 'z-index';
83 return function (css, result) {
84 css.walkDecls(filter, function (decl) {
90 postcss([ remove ]) // with default options
91 postcss([ remove({ prop: 'color' })]) // with options
96 * `name (string)`: PostCSS plugin name. Same as in `name` property
97 in `package.json`. It will be saved in `plugin.postcssPlugin` property.
98 * `initializer (function)`: will receive plugin options and should return
99 functions to modify nodes in input CSS.
101 The newly-wrapped function will provide both the name and PostCSS
102 version of the plugin:
105 var processor = postcss([replace]);
106 processor.plugins[0].postcssPlugin //=> 'postcss-replace'
107 processor.plugins[0].postcssVersion //=> '4.1.0'
110 The plugin function receives 2 arguments: [`Root` node] and [`Result`] instance.
111 The function should mutate the provided `Root` node. Alternatively, you can
112 create a new `Root` node and override the `result.root` property.
115 var cleaner = postcss.plugin('postcss-cleaner', function () {
116 return function (css, result) {
117 result.root = postcss.root();
122 As a convenience, plugins also expose a `process` method so that you can use
123 them as standalone tools.
126 cleaner.process(css, options);
127 // This is equivalent to:
128 postcss([ cleaner(options) ]).process(css);
131 Asynchronous plugins should return a `Promise` instance.
134 postcss.plugin('postcss-import', function () {
135 return function (css, result) {
136 return new Promise(function (resolve, reject) {
137 fs.readFile('base.css', function (base) {
146 Add warnings using the [`Node#warn()`] method.
149 postcss.plugin('postcss-caniuse-test', function () {
150 return function (css, result) {
151 css.walkDecls(function (decl) {
152 if ( !caniuse.support(decl.prop) ) {
154 'Some browsers do not support ' + decl.prop);
161 Send data to other plugins using the [`Result#messages`] array.
163 ### `postcss.root(props)`
165 Creates a new [`Root` node].
168 postcss.root({ after: '\n' }).toString() //=> "\n"
173 * `props (object) optional`: properties for the new root node.
175 ### `postcss.atRule(props)`
177 Creates a new [`AtRule` node].
180 postcss.atRule({ name: 'charset' }).toString() //=> "@charset"
185 * `props (object) optional`: properties for the new at-rule node.
187 ### `postcss.rule(props)`
189 Creates a new [`Rule` node].
192 postcss.rule({ selector: 'a' }).toString() //=> "a {\n}"
197 * `props (object) optional`: properties for the new rule node.
199 ### `postcss.decl(props)`
201 Creates a new [`Declaration` node].
204 postcss.decl({ prop: 'color', value: 'black' }).toString() //=> "color: black"
209 * `props (object) optional`: properties for the new declaration node.
211 ### `postcss.comment(props)`
213 Creates a new [`Comment` node].
216 postcss.comment({ text: 'test' }).toString() //=> "/* test */"
221 * `props (object) optional`: properties for the new comment node.
225 Contains the [Vendor module](#vendor-module).
228 postcss.vendor.unprefixed('-moz-tab') //=> ['tab']
233 Contains the [List module](#list-module).
236 postcss.list.space('5px calc(10% + 5px)') //=> ['5px', 'calc(10% + 5px)']
239 ### `postcss.stringify(node, builder)`
241 Default function to convert a node tree into a CSS string.
245 A `Processor` instance contains plugins to process CSS. Create
246 one `Processor` instance, initialize its plugins, and then use that instance
247 on numerous CSS files.
250 var processor = postcss([autoprefixer, cssnext, cssgrace]);
251 processor.process(css1).css;
252 processor.process(css2).css;
255 ### `processor.use(plugin)`
257 Adds a plugin to be used as a CSS processor.
260 var processor = postcss();
261 processor.use(autoprefixer()).use(cssnext()).use(cssgrace());
266 * `plugin (function|#postcss|Processor)`: PostCSS plugin. It can be in three
268 * A plugin created by [`postcss.plugin()`] method.
269 * A function. PostCSS will pass the function a [`Root` node]
270 as the first argument and current [`Result`] instance as the second.
271 * An object with a `postcss` method. PostCSS will use that method
273 * Another `Processor` instance. PostCSS will copy plugins
274 from that instance into this one.
276 Plugins can also be added by passing them as arguments when creating
277 a `postcss` instance (see [`postcss(plugins)`]).
279 Asynchronous Plugins should return a `Promise` instance.
281 ### `processor.process(css, opts)`
283 Parses source CSS and returns a [`LazyResult`] instance. Because some plugins
284 can be asynchronous it doesn’t make any transformations. Transformations will
285 be applied in the `LazyResult`’s methods.
288 processor.process(css, { from: 'a.css', to: 'a.out.css' }).then(function (result) {
289 console.log(result.css);
295 * `css (string|#toString|Result)`: String with input CSS or any object
296 with a `toString()` method, like a Buffer. Optionally, send a [`Result`]
297 instance and the processor will take the existing [`Root`] parser from it.
298 * `opts (object) optional`: options:
299 * `from`: the path of the CSS source file. You should always set `from`,
300 because it is used in source map generation and syntax error messages.
301 * `to`: the path where you’ll put the output CSS file. You should always set
302 `to` to generate correct source maps.
303 * `parser`: function to generate AST by string.
304 * `stringifier`: class to generate string by AST.
305 * `syntax`: object with `parse` and `stringify` functions.
306 * `map`: an object of [source map options].
308 ### `processor.plugins`
310 Contains plugins added to this processor.
313 var processor = postcss([cssnext, cssgrace]);
314 processor.plugins.length //=> 2
317 ### `processor.version`
319 Contains the current version of PostCSS.
322 postcss().version //=> '4.0.5'
325 ## `LazyResult` class
327 A promise proxy for the result of PostCSS transformations.
329 A `LazyResult` instance is returned by [`Processor#process(css, opts)`].
332 var lazy = postcss([cssnext]).process(css);
335 ### `lazy.then(onFulfilled, onRejected)`
337 Processes input CSS through synchronous and asynchronous plugins
338 and calls `onFulfilled` with a [`Result`] instance. If a plugin throws
339 an error, the `onRejected` callback will be executed.
342 postcss([cssnext]).process(css).then(function(result) {
343 console.log(result.css);
347 This method is a standard [Promise] method.
349 ### `lazy.catch(onRejected)`
351 Processes input CSS through synchronous and asynchronous plugins
352 and calls `onRejected` for each error thrown in any plugin.
355 postcss([cssnext]).process(css).then(function(result) {
356 console.log(result.css);
357 }).catch(function (error) {
358 console.error(error);
362 This method is a standard [Promise] method.
364 ### `lazy.toString()`
366 Alias for the `LazyResult#css` property.
370 Processes input CSS through synchronous plugins, converts `Root` to a CSS
371 string and returns [`Result#css`].
374 processor.process(css).css;
377 This property will only work with synchronous plugins. If the processor
378 contains any asynchronous plugins it will throw an error. In this case,
379 you should use [`LazyResult#then()`] instead.
382 postcss([cssnext]).then(function (result) {
383 console.log(result.css);
389 An alias for the `css` property. Use it with syntaxes that generate non-CSS
393 lazy.css === lazy.content;
398 Processes input CSS through synchronous plugins and returns [`Result#map`].
402 fs.writeFileSync(result.opts.to + '.map', result.map.toString());
406 This property will only work with synchronous plugins. If the processor
407 contains any asynchronous plugins it will throw an error. In this case,
408 you should use [`LazyResult#then()`] instead.
411 postcss([cssnext]).then(function (result) {
413 fs.writeFileSync(result.opts.to + '.map', result.map.toString());
420 Processes input CSS through synchronous plugins and returns
421 [`Result#root`](#resultroot).
423 This property will only work with synchronous plugins. If the processor
424 contains any asynchronous plugins it will throw an error. In this case,
425 you should use [`LazyResult#then()`] instead.
428 postcss([cssnext]).then(function (result) {
429 console.log(result.root);
433 ### `lazy.warnings()`
435 Processes input CSS through synchronous plugins and calls [`Result#warnings()`].
438 postcss([cssnext]).warnings().forEach(function (message) {
439 console.warn(message.text);
443 This property will only work with synchronous plugins. If the processor
444 contains any asynchronous plugins it will throw an error. In this case,
445 you should use [`LazyResult#then()`] instead.
448 postcss([cssnext]).then(function (result) {
449 result.warnings().forEach(function (message) {
450 console.warn(message.text);
457 Processes input CSS through synchronous plugins and returns [`Result#messages`].
459 This property will only work with synchronous plugins. If the processor
460 contains any asynchronous plugins it will throw an error. In this case,
461 you should use [`LazyResult#then()`] instead.
465 Returns a [`Processor`] instance, which will be used for CSS transformations.
468 var lazy = postcss([cssnext, cssgrace]).process(css);
469 lazy.processor.plugins.length //=> 2
474 Options from the [`Processor#process(css, opts)`] call that produced
475 this `Result` instance.
478 postcss().process(css, opts).opts == opts;
483 Provides the result of the PostCSS transformations.
485 A `Result` instance is returned by [`Root#toResult(opts)`]
486 or [`LazyResult#then()`] methods.
489 postcss([cssnext]).process(css).then(function (result1) {
490 console.log(result1.css);
492 var result2 = postcss.parse(css).toResult();
495 ### `result.toString()`
497 Alias for [`Result#css`] property.
499 ### `result.warn(text, opts)`
501 Creates an instance of [`Warning`] and adds it to [`Result#messages`].
504 var plugin = postcss.plugin('postcss-important', function () {
505 return function (css, result) {
506 css.walkDecls(function (decl) {
507 if ( decl.important ) {
508 result.warn('Try to avoid !important', { node: decl });
514 postcss([plugin]).process(css).then(function (result) {
515 result.warnings() //=> [{
516 // plugin: 'postcss-important-warning',
517 // text: 'Try to avoid !important'
518 // node: { type: 'decl', … }
525 * `text (string)`: warning message. It will be used in the `text` property of
527 * `opts (object) optional`: properties to assign to the message object.
528 * `node`: CSS node that was the source of the warning.
529 * `word (string)`: word inside a node’s string that should be highlighted
530 as the source of the warning.
531 * `index` (number): index inside a node’s string that should be highlighted
532 as the source of the warning.
533 * `plugin`: name of the plugin that created this warning. `Result#warn()` will
534 automatically fill it with the `plugin.postcssPlugin` value.
536 ### `result.warnings()`
538 Returns warnings from plugins. Filters [`Warning`] instances
539 from [Result#messages].
542 result.warnings().forEach(function (message) {
543 console.log(message.toString());
549 A CSS string representing this `Result`’s '`Root` instance.
552 postcss.parse('a{}').toResult().css //=> "a{}"
557 An alias for the `css` property. Use it with syntaxes that generate non-CSS
561 result.css === result.content;
566 An instance of the `SourceMapGenerator` class from the [`source-map`] library,
567 representing changes to the `Result`’s `Root` instance.
570 result.map.toJSON() //=> { version: 3, file: 'a.css', sources: ['a.css'], … }
573 This property will have a value *only if the user does not want an inline source
574 map*. By default, PostCSS generates inline source maps, written directly into
575 the processed CSS. The `map` property will be empty by default.
577 An external source map will be generated — and assigned to `map` —
578 only if the user has set the `map.inline` option to `false`, or if PostCSS
579 was passed an external input source map.
583 fs.writeFileSync(result.opts.to + '.map', result.map.toString());
589 Contains the [`Root` node] after all transformations.
592 root.toResult().root == root;
595 ### `result.messages`
597 Contains messages from plugins (e.g., warnings or custom messages).
599 Each message should have `type` and `plugin` properties.
602 postcss.plugin('postcss-min-browser', function () {
603 return function (css, result) {
604 var browsers = detectMinBrowsersByCanIUse(css);
605 result.messages.push({
607 plugin: 'postcss-min-browser',
614 Add a warning using [`Result#warn()`] and get all warnings
615 using the [`Result#warnings()`](#resultwarnings) method.
617 ### `result.processor`
619 Returns the [`Processor`] instance used for this transformation.
622 result.processor.plugins.forEach(function (plugin) {
623 if ( plugin.postcssPlugin == 'postcss-bad' ) {
624 throw 'postcss-good is incompatible with postcss-bad';
631 Options from the [`Processor#process(css, opts)`] or [`Root#toResult(opts)`]
632 call that produced this `Result` instance.
635 root.toResult(opts).opts == opts;
640 Represents a plugin warning. It can be created using [`Node#warn()`].
643 if ( decl.important ) {
644 decl.warn(result, 'Try to avoid !important');
648 ### `warning.toString()`
650 Returns a string with the error position and message.
653 warning.toString() //=> 'postcss-important:a.css:10:4: Try to avoid !important'
658 Contains the warning message.
661 warning.text //=> 'Try to avoid !important'
666 Contains the name of the plugin that created this warning. When you call
667 [`Node#warn()`] it will fill this property automatically.
670 warning.plugin //=> 'postcss-important'
675 Contains the CSS node that caused the warning.
678 warning.node.toString() //=> 'color: white !important'
683 The line in the input file with this warning’s source.
691 Column in the input file with this warning’s source.
694 warning.column //=> 4
697 ## `CssSyntaxError` class
699 The CSS parser throws this error for broken CSS.
702 postcss.parse('a{') //=> CssSyntaxError
705 Custom parsers can throw this error for broken custom syntax
706 using the [`Node#error()`](#nodeerrormessage) method.
709 throw node.error('Unknown variable', { plugin: 'postcss-vars' });
712 ### `error.toString()`
714 Returns a string with the error position, message and source code of the
718 error.toString() //=> CssSyntaxError: app.css:1:1: Unclosed block
723 ### `error.showSourceCode(color)`
725 Returns a few lines of CSS source that caused the error.
728 error.showSourceCode() //=>
737 * `color (boolean) optional`: whether arrow will be colored red by terminal
738 color codes. By default, PostCSS will use `process.stdout.isTTY` and
739 `process.env.NODE_DISABLE_COLORS`.
741 If the CSS has an input source map without `sourceContent`, this method will
742 return an empty string.
746 Contains full error text in the GNU error format.
749 error.message //=> 'a.css:1:1: Unclosed block'
754 Contains only the error description.
757 error.reason //=> 'Unclosed block'
762 Contains the PostCSS plugin name if the error didn’t come from the CSS parser.
765 error.plugin //=> 'postcss-vars'
768 PostCSS will fill it automatically.
772 Contains the absolute path to the broken file. If you use it, send the `from`
773 option to the parser.
776 error.file //=> 'a.sass'
779 PostCSS will use the input source map to detect the original error location.
780 If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
781 PostCSS will show the original position in the Sass file.
783 If you need the position in the PostCSS input (e.g., to debug the previous
784 compiler), use `error.input.file`.
787 error.file //=> 'a.sass'
788 error.input.file //=> 'a.css'
793 Contains the source line of the error.
799 PostCSS will use the input source map to detect the original error location.
800 If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
801 PostCSS will show the original position in the Sass file.
803 If you need the position in the PostCSS input (e.g., to debug the previous
804 compiler), use `error.input.file`.
808 error.input.line //=> 4
813 Contains the source column of the error.
819 PostCSS will use the input source map to detect the original error location.
820 If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
821 PostCSS will show the original position in the Sass file.
823 If you need the position in the PostCSS input (e.g., to debug the previous
824 compiler), use `error.input.file`.
828 error.input.column //=> 4
833 Contains the source code of the broken file.
836 error.source //=> 'a {} b {'
839 PostCSS will use the input source map to detect the original error location.
840 If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
841 PostCSS will show the original position in the Sass file.
843 If you need the position in the PostCSS input (e.g., to debug the previous
844 compiler), use `error.input.file`.
847 error.source //=> 'a { b {} }'
848 error.input.column //=> 'a b { }'
853 Contains helpers for working with vendor prefixes.
856 var vendor = postcss.vendor;
859 ### `vendor.prefix(string)`
861 Returns the vendor prefix extracted from an input string.
864 postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
867 ### `vendor.unprefixed(string)`
869 Returns the input string stripped of its vendor prefix.
872 postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
877 Contains helpers for safely splitting lists of CSS values,
878 preserving parentheses and quotes.
881 var list = postcss.list;
884 ### `list.space(string)`
886 Safely splits space-separated values (such as those for `background`,
887 `border-radius`, and other shorthand properties).
890 postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
893 ### `list.comma(string)`
895 Safely splits comma-separated values (such as those
896 for `transition-*` and `background` properties).
899 postcss.list.comma('black, linear-gradient(white, black)')
900 //=> ['black', 'linear-gradient(white, black)']
905 Represents the source CSS.
908 var root = postcss.parse(css, { from: file });
909 var input = root.source.input;
914 The absolute path to the CSS source file defined with the [`from` option].
917 var root = postcss.parse(css, { from: 'a.css' });
918 root.source.input.file //=> '/home/ai/a.css'
923 The unique ID of the CSS source. Used if `from`
924 option is not provided (because PostCSS does not know the file path).
927 var root = postcss.parse(css);
928 root.source.input.file //=> undefined
929 root.source.input.id //=> <input css 1>
934 The CSS source identifier. Contains [`input.file`](#inputfile) if the user set
935 the [`from` option], or [`input.id`](#inputid) if they did not.
938 var root = postcss.parse(css, { from: 'a.css' });
939 root.source.input.from //=> '/home/ai/a.css'
941 var root = postcss.parse(css);
942 root.source.input.from //=> <input css 1>
947 Represents the input source map passed from a compilation step before PostCSS
948 (e.g., from the Sass compiler).
950 `map.consumer()` returns an instance of the `SourceMapConsumer` class
951 from the [`source-map`] library.
954 root.source.input.map.consumer().sources //=> ['a.sass']
957 ### `input.origin(line, column)`
959 Reads the input source map and returns a symbol position in the input source
960 (e.g., in a Sass file that was compiled to CSS before being passed
964 root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
967 ## Nodes: common methods
969 All node classes inherit the following common methods.
973 Returns a string representing the node’s type.
975 Possible values are `root`, `atrule`, `rule`, `decl`, or `comment`.
978 postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
983 Returns the node’s parent node.
986 root.nodes[0].parent == root;
991 Returns the input source of the node, with the following properties:
993 - `node.source.input`: An [`Input`] instance.
994 - `node.source.start`: The starting position of the node’s source —
996 - `node.source.end`: The ending position of the node’s source — line and column.
999 decl.source.input.from //=> '/home/ai/a.sass'
1000 decl.source.start //=> { line: 10, column: 2 }
1001 decl.source.end //=> { line: 10, column: 12 }
1004 The property is used in source map generation.
1006 If you create a node manually (e.g., with `postcss.decl()`),
1007 that node will not have a `source` property and will be absent
1008 from the source map. For this reason, the plugin developer should consider
1009 cloning nodes to create new ones (in which case the new node’s source
1010 will reference the original, cloned node) or setting the `source` property
1015 var prefixed = postcss.decl({ prop: '-moz-' + decl.prop, value: decl.value });
1018 var prefixed = decl.clone({ prop: '-moz-' + decl.prop });
1022 if ( atrule.name == 'add-link' ) {
1023 var rule = postcss.rule({ selector: 'a' }); // Rule has no source
1024 atrule.parent.insertBefore(atrule, rule); // We add it because of atrule
1025 rule.source = atrule.source; // So we copy source from atrule
1031 Contains information to generate byte-to-byte equal node string
1032 as it was in the origin input.
1034 Every parser saves its own properties, but the default CSS parser uses:
1036 * `before`: the space symbols before the node. It also stores `*` and `_`
1037 symbols before the declaration (IE hack).
1038 * `after`: the space symbols after the last child of the node to the end of the
1040 * `between`: the symbols between the property and value for declarations,
1041 selector and `{` for rules, or last parameter and `{` for at-rules.
1042 * `semicolon`: contains `true` if the last child has an (optional) semicolon.
1043 * `afterName`: the space between the at-rule’s name and its parameters.
1044 * `left`: the space symbols between `/*` and the comment’s text.
1045 * `right`: the space symbols between the comment’s text and `*/`.
1046 * `important`: the content of the important statement,
1047 if it is not just `!important`.
1049 PostCSS cleans selectors, declaration values and at-rule parameters
1050 from comments and extra spaces, but it stores origin content
1051 in `raws` properties. As such, if you don’t change a declaration’s value,
1052 PostCSS will use the raw value with comments.
1054 ### `node.toString()`
1056 Returns a CSS string representing the node.
1059 postcss.rule({ selector: 'a' }).toString() //=> 'a {}''
1064 * `stringifier (functions|object) optional`: a syntax to use
1065 in string generation.
1067 ### `node.error(message, opts)`
1069 Returns a [`CssSyntaxError`] instance containing the original position
1070 of the node in the source, showing line and column numbers and also
1071 a small excerpt to facilitate debugging.
1073 If present, an input source map will be used to get the original position
1074 of the source, even from a previous compilation step
1075 (e.g., from Sass compilation).
1077 This method produces very useful error messages.
1080 if ( !variables[name] ) {
1081 throw decl.error('Unknown variable ' + name, { word: name });
1082 // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
1086 // background: white
1092 * `message (string)`: error description.
1093 * `opts (object) optional`: options.
1094 * `plugin (string)`: plugin name that created this error.
1095 PostCSS will set it automatically.
1096 * `word (string)`: a word inside a node’s string that should be highlighted
1097 as the source of the error.
1098 * `index` (number): an index inside a node’s string that should be highlighted
1099 as the source of the error.
1101 ### `node.warn(result, text, opts)`
1103 This method is provided as a convenience wrapper for [`Result#warn()`].
1106 var plugin = postcss.plugin('postcss-deprecated', function () {
1107 return function (css, result) {
1108 css.walkDecls('bad', function (decl) {
1109 decl.warn(result, 'Deprecated property bad');
1117 * `result`: The [`Result`] instance that will receive the warning.
1118 * `text (string)`: warning message. It will be used in the `text` property of
1120 * `opts (object) optional`: properties to assign to the message object.
1121 * `word (string)`: word inside a node’s string that should be highlighted
1122 as the source of the warning.
1123 * `index` (number): index inside a node’s string that should be highlighted
1124 as the source of the warning.
1125 * `plugin`: name of the plugin that created this warning. `Result#warn()` will
1126 automatically fill it with the `plugin.postcssPlugin` value.
1128 Note that `opts.node` is automatically passed to [`Result#warn()`] for you.
1130 ### `node.next()` and `node.prev()`
1132 Returns the next/previous child of the node’s parent.
1133 Returns `undefined` if the current node is the last/first child.
1136 var annotation = decl.prev();
1137 if ( annotation.type == 'comment' ) {
1138 readAnnotation( annotation.text );
1144 Returns the `Root` instance of the node’s tree.
1147 root.nodes[0].nodes[0].root() == root
1152 Removes the node from its parent and cleans the `parent` properties from the
1153 node and its children.
1156 if ( decl.prop.match(/^-webkit-/) ) {
1161 ### `node.replaceWith(...otherNodes)`
1163 Inserts node(s) before the current node and removes the current node.
1166 if ( atrule.name == 'mixin' ) {
1167 atrule.replaceWith(mixinRules[atrule.params]);
1171 ### `node.clone(props)`
1173 Returns a clone of the node.
1175 The resulting cloned node and its (cloned) children will have a clean `parent`
1176 and code style properties.
1179 var cloned = decl.clone({ prop: '-moz-' + decl.prop });
1180 cloned.raws.before //=> undefined
1181 cloned.parent //=> undefined
1182 cloned.toString() //=> -moz-transform: scale(0)
1187 * `props (object) optional`: new properties to override in the clone.
1189 ### `node.cloneBefore(props)` and `node.cloneAfter(props)`
1191 Shortcut to clone the node and insert the resulting cloned node before/after
1195 decl.cloneBefore({ prop: '-moz-' + decl.prop });
1200 * `props (object) optional`: new properties to override in the clone.
1202 ### `node.moveTo(newParent)`
1204 Removes the node from its current parent and inserts it
1205 at the end of `newParent`.
1207 This will clean the `before` and `after` code style properties from the node
1208 and replace them with the indentation style of `newParent`. It will also clean
1209 the `between` property if `newParent` is in another `Root`.
1212 atrule.moveTo(atrule.parent.parent);
1217 * `newParent: (Container)`: container node where the current node will be moved.
1219 ### `node.moveBefore(otherNode)` and `node.moveAfter(otherNode)`
1221 Removes the node from its current parent and inserts it into a new parent
1222 before/after `otherNode`.
1224 This will also clean the node’s code style properties just as it would in
1225 `node.moveTo(newParent)`.
1229 * `otherNode (Node)`: node that will be after/before current node after moving.
1231 ### `node.raw(prop, defaultType)`
1233 Returns a code style property value. If the node is missing the code style
1234 property (because the node was manually built or cloned), PostCSS will try
1235 to autodetect the code style property by looking at other nodes in the tree.
1238 var root = postcss.parse('a { background: white }');
1239 root.nodes[0].append({ prop: 'color', value: 'black' });
1240 root.nodes[0].nodes[1].raws.before //=> ' '
1245 * `prop (string)`: name or code style property.
1246 * `defaultType (string)`: name of default value. It can be easily missed
1247 if the value is the same as `prop`.
1249 ## Containers: common methods
1251 The `Root`, `AtRule`, and `Rule` container nodes inherit some common methods
1252 to help work with their children.
1254 Note that all containers can store *any* content. If you write a rule inside
1255 a rule, PostCSS will parse it.
1257 ### `container.nodes`
1259 An array containing the container’s children.
1262 var root = postcss.parse('a { color: black }');
1263 root.nodes.length //=> 1
1264 root.nodes[0].selector //=> 'a'
1265 root.nodes[0].nodes[0].prop //=> 'color'
1268 ### `container.first`
1270 The container’s first child.
1273 rule.first == rules.nodes[0];
1276 ### `container.last`
1278 The container’s last child.
1281 rule.last == rule.nodes[rule.nodes.length - 1];
1284 ### `container.index(child)`
1286 Returns a `child`’s index within the container’s `nodes` array.
1289 rule.index( rule.nodes[2] ) //=> 2
1294 * `child (Node)`: child of the current container.
1296 ### `container.every(callback)`
1298 Returns `true` if `callback` returns true for all of the container’s children.
1301 var noPrefixes = rule.every(function (decl) {
1302 return decl.prop[0] != '-';
1308 * `callback (function)`: iterator. Returns true or false.
1310 ### `container.some(callback)`
1312 Returns `true` if `callback` returns true for (at least) one
1313 of the container’s children.
1316 var hasPrefix = rule.some(function (decl) {
1317 return decl.prop[0] == '-';
1323 * `callback (function)`: iterator. Returns true or false.
1325 ### `container.each(callback)`
1327 Iterates through the container’s immediate children, calling `callback`
1330 Returning `false` in the `callback` will break iteration.
1334 rule.each(function (decl) {
1335 if ( decl.prop == 'color' ) {
1344 * `callback (function)`: iterator. Receives each node and its index.
1346 Unlike the `for {}`-cycle or `Array#forEach()` this iterator is safe
1347 if you are mutating the array of child nodes during iteration.
1348 PostCSS will adjust the current index to match the mutations.
1351 var root = postcss.parse('a { color: black; z-index: 1 }');
1352 var rule = root.first;
1354 for ( var i = 0; i < rule.nodes.length; i++ ) {
1355 var decl = rule.nodes[i];
1356 decl.cloneBefore({ prop: '-webkit-' + decl.prop });
1357 // Cycle will be infinite, because cloneBefore moves the current node
1358 // to the next index
1361 rule.each(function (decl) {
1362 decl.cloneBefore({ prop: '-webkit-' + decl.prop });
1363 // Will be executed only for color and z-index
1367 `container.each()` only iterates through the container’s immediate children.
1368 If you need to recursively iterate through all the container’s descendant nodes,
1369 use `container.walk()`.
1371 ### `container.walk(callback)`
1373 Traverses the container’s descendant nodes, calling `callback` for each node.
1376 root.walk(function (node) {
1377 // Traverses all descendant nodes.
1383 * `callback (function)`: iterator. Receives each node and its index.
1385 Like `container.each()`, this method is safe to use
1386 if you are mutating arrays during iteration.
1388 If you only need to iterate through the container’s immediate children,
1389 use `container.each()`.
1391 ### `container.walkDecls([propFilter,] callback)`
1393 Traverses the container’s descendant nodes, calling `callback` for each
1397 root.walkDecls(function (decl) {
1398 if ( decl.prop.match(/^-webkit-/) ) {
1406 * `propFilter: (string|RegExp) optional`: string or regular expression
1407 to filter declarations by property name.
1408 * `callback (function)`: iterator. Receives each declaration node and its
1411 If you pass a `propFilter`, iteration will only happen over declarations with
1412 matching properties.
1415 // Make a flat design
1416 root.walkDecls('border-radius', function (decl) {
1419 root.walkDecls(/^background/, function (decl) {
1420 decl.value = takeFirstColorFromGradient(decl.value);
1424 Like `container.each()`, this method is safe to use if you are mutating
1425 arrays during iteration.
1427 ### `container.walkAtRules([nameFilter,] callback)`
1429 Traverses the container’s descendant nodes, calling `callback` for each
1433 root.walkAtRules(function (rule) {
1434 if ( rule.name.match(/^-webkit-/) ) rule.remove();
1440 * `nameFilter: (string|RegExp) optional`: string or regular expression to filter
1442 * `callback (function)`: iterator. Receives each at-rule and its index.
1444 If you pass a `filter`, iteration will only happen over at-rules that have
1449 root.walkAtRules('charset', function (rule) {
1458 Like `container.each()`, this method is safe to use if you are mutating arrays
1461 ### `container.walkRules([selectorFilter,] callback)`
1463 Traverses the container’s descendant nodes, calling `callback` for each
1468 root.walkRules(function (rule) {
1469 selectors.push(rule.selector);
1471 console.log('Your CSS uses ' + selectors.length + ' selectors');
1476 * `selectorFilter: (string|RegExp) optional`: string or regular expression
1477 to filter rules by selector.
1478 * `callback (function)`: iterator. Receives each rule node and its index.
1480 If you pass a `selectorFilter`, iteration will only happen over rules with
1483 Like `container.each()`, this method is safe to use if you are mutating arrays
1486 ### `container.walkComments(callback)`
1488 Traverses the container’s descendant nodes, calling `callback` for each
1492 root.walkComments(function (comment) {
1499 * `callback (function)`: iterator. Receives each comment node and its index.
1501 Like `container.each()`, this method is safe to use if you are mutating arrays
1504 ### `container.replaceValues(pattern, opts, callback)`
1506 Passes all declaration values within the container that match `pattern` through
1507 `callback`, replacing those values with the returned result of `callback`.
1509 This method is useful if you are using a custom unit or function and need
1510 to iterate through all values.
1513 root.replaceValues(/\d+rem/, { fast: 'rem' }, function (string) {
1514 return 15 * parseInt(string) + 'px';
1520 * `pattern (string|RegExp)`: replace pattern.
1521 * `opts (object) optional`: options to speed up the search:
1522 * `props`: An array of property names. The method will only search for values
1523 that match `regexp` within declarations of listed properties.
1524 * `fast`: A string that’s used to narrow down values and speed up
1525 the regexp search. Searching every single value with a regexp can be slow.
1526 If you pass a `fast` string, PostCSS will first check whether the value
1527 contains the `fast` string; and only if it does will PostCSS check that
1528 value against `regexp`. For example, instead of just checking for `/\d+rem/`
1529 on all values, set `fast: 'rem'` to first check whether a value has
1530 the `rem` unit, and only if it does perform the regexp check.
1531 * `callback (function|string)`: string to replace `pattern` or callback that
1532 returns a new value. The callback will receive the same arguments as those
1533 passed to a function parameter of [`String#replace`].
1535 [`String#replace`]: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter)
1537 ### `container.prepend(...nodes)` and `container.append(...nodes)`
1539 Inserts new nodes to the start/end of the container.
1542 var decl = postcss.decl({ prop: 'color', value: 'black' });
1547 var decl1 = postcss.decl({ prop: 'color', value: 'black' });
1548 var decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
1549 rule.prepend(decl1, decl2);
1554 * `node (Node|array|object|string)`: new node.
1556 Because each node class is identifiable by unique properties, use
1557 the following shortcuts to create nodes in insert methods:
1560 root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
1561 root.append({ selector: 'a' }); // rule
1562 rule.append({ prop: 'color', value: 'black' }); // declaration
1563 rule.append({ text: 'Comment' }) // comment
1566 A string containing the CSS of the new element can also be used.
1567 This approach is slower than the above shortcuts.
1570 root.append('a {}');
1571 root.first.append('color: black; z-index: 1');
1574 ### `container.insertBefore(oldNode, newNode)` and `container.insertAfter(oldNode, newNode)`
1576 Insert `newNode` before/after `oldNode` within the container.
1579 rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
1584 * `oldNode (Node|number)`: child or child’s index.
1585 * `node (Node|array|object|string)`: new node.
1587 ### `container.removeChild(node)`
1589 Removes `node` from the container and cleans the `parent` properties from the
1590 node and its children.
1593 rule.nodes.length //=> 5
1594 rule.removeChild(decl);
1595 rule.nodes.length //=> 4
1596 decl.parent //=> undefined
1601 * `node (Node|number)`: child or child’s index.
1603 ### `container.removeAll()`
1605 Removes all children from the container and cleans their `parent` properties.
1609 rule.nodes.length //=> 0
1614 Represents a CSS file and contains all its parsed nodes.
1617 var root = postcss.parse('a{color:black} b{z-index:2}');
1618 root.type //=> 'root'
1619 root.nodes.length //=> 2
1622 ### `root.toResult(opts)`
1624 Returns a [`Result`] instance representing the root’s CSS.
1627 var root1 = postcss.parse(css1, { from: 'a.css' });
1628 var root2 = postcss.parse(css2, { from: 'b.css' });
1630 root1.append(root2);
1631 var result = root1.toResult({ to: 'all.css', map: true });
1636 * `opts (object) optional`: options:
1637 * `to`: the path where you’ll put the output CSS file. You should always set
1638 `to` to generate correct source maps.
1639 * `map`: an object of [source map options].
1643 Represents an at-rule.
1645 If it’s followed in the CSS by a `{}` block, this node will have a `nodes`
1646 property representing its children.
1650 var root = postcss.parse('@charset "UTF-8"; @media print {}');
1652 var charset = root.first;
1653 charset.type //=> 'atrule'
1654 charset.nodes //=> undefined
1656 var media = root.last;
1662 The at-rule’s name. This is the identifier that immediately follows the `@`.
1665 var root = postcss.parse('@media print {}');
1666 var media = root.first;
1667 media.name //=> 'media'
1672 The at-rule’s parameters. These are the values that follow the at-rule’s name
1673 but precede any `{}` block. The spec refers to this area
1674 as the at-rule’s “prelude”.
1677 var root = postcss.parse('@media print, screen {}');
1678 var media = root.first;
1679 media.params //=> 'print, screen'
1684 Represents a CSS rule: a selector followed by a declaration block.
1687 var root = postcss.parse('a{}');
1688 var rule = root.first;
1689 rule.type //=> 'rule'
1690 rule.toString() //=> 'a{}'
1695 The rule’s full selector represented as a string. If there are multiple
1696 comma-separated selectors, the entire group will be included.
1699 var root = postcss.parse('a, b { }');
1700 var rule = root.first;
1701 rule.selector //=> 'a, b'
1704 ### `rule.selectors`
1706 An array containing the rule’s individual selectors.
1707 Groups of selectors are split at commas.
1710 var root = postcss.parse('a, b { }');
1711 var rule = root.first;
1713 rule.selector //=> 'a, b'
1714 rule.selectors //=> ['a', 'b']
1716 rule.selectors = ['a', 'strong'];
1717 rule.selector //=> 'a, strong'
1720 ## `Declaration` node
1722 Represents a CSS declaration.
1725 var root = postcss.parse('a { color: black }');
1726 var decl = root.first.first;
1727 decl.type //=> 'decl'
1728 decl.toString() //=> ' color: black'
1731 ### `declaration.prop`
1733 The declaration’s property name.
1736 var root = postcss.parse('a { color: black }');
1737 var decl = root.first.first;
1738 decl.prop //=> 'color'
1741 ### `declaration.value`
1743 The declaration’s value.
1746 var root = postcss.parse('a { color: black }');
1747 var decl = root.first.first;
1748 decl.value //=> 'black'
1751 ### `declaration.important`
1753 `true` if the declaration has an `!important` annotation.
1756 var root = postcss.parse('a { color: black !important; color: white }');
1757 root.first.first.important //=> true
1758 root.first.last.important //=> undefined
1763 Represents a comment between declarations or statements (rule and at-rules).
1764 Comments inside selectors, at-rule parameters, or declaration values
1765 will be stored in the [`Node#raws`] properties explained above.
1768 var root = postcss.parse('a { color: /* inner */ black; /* outer */ }');
1769 var decl = root.first.first;
1770 var comment = root.first.last;
1772 comment.type //=> 'comment'
1773 decl.between //=> ': /* inner */'
1781 var root = postcss.parse('/* Empty file */');
1782 var comment = root.first;
1783 var comment.text //=> 'Empty file'
1786 [`source-map`]: https://github.com/mozilla/source-map
1787 [Promise]: http://www.html5rocks.com/en/tutorials/es6/promises/
1789 [source map options]: https://github.com/postcss/postcss/blob/master/docs/source-maps.md
1791 [`Processor#process(css, opts)`]: #processorprocesscss-opts
1792 [`Root#toResult(opts)`]: #roottoresultopts
1793 [`LazyResult#then()`]: #lazythenonfulfilled-onrejected
1794 [`postcss(plugins)`]: #postcssplugins
1795 [`postcss.plugin()`]: #postcsspluginname-initializer
1796 [`Declaration` node]: #declaration-node
1797 [`Result#messages`]: #resultmessages
1798 [`CssSyntaxError`]: #csssyntaxerror-class
1799 [`Processor#use`]: #processoruseplugin
1800 [`Result#warn()`]: #resultwarntext-opts
1801 [`Node#warn()`]: #nodewarnresult-message
1802 [`Comment` node]: #comment-node
1803 [`AtRule` node]: #atrule-node
1804 [`from` option]: #processorprocesscss-opts
1805 [`LazyResult`]: #lazyresult-class
1806 [`Result#map`]: #resultmap
1807 [`Result#css`]: #resultcss
1808 [`Root` node]: #root-node
1809 [`Rule` node]: #rule-node
1810 [`Processor`]: #processor-class
1811 [`Node#raws`]: #noderaws
1812 [`Warning`]: #warning-class
1813 [`Result`]: #result-class
1814 [`Input`]: #inputclass