PostCSS is a tool for transforming CSS with JS plugins. These plugins can support variables and mixins, transpile future CSS syntax, inline images, and more.
PostCSS is used by industry leaders including Google, Twitter, Alibaba, and Shopify. The Autoprefixer PostCSS plugin is one of the most popular CSS processors.
PostCSS can do the same work as preprocessors like Sass, Less, and Stylus. But PostCSS is modular, 3-30 times faster, and much more powerful.
Twitter account: @postcss. VK.com page: postcss.
| Examples | Features | Usage | Plugins | Write Your Own Plugin | Options |
|---|
What is PostCSS
PostCSS itself is very small. It includes only a CSS parser, a CSS node tree API, a source map generator, and a node tree stringifier.
All CSS transformations are made by plugins. And these plugins are just small plain JS functions, which receive a CSS node tree, transform it, and return a modified tree.
You can use the cssnext plugin pack and write future CSS code right now:
:root { --mainColor: #ffbbaaff; } @custom-media --mobile (width <= 640px); @custom-selector --heading h1, h2, h3, h4, h5, h6; .post-article :--heading { color: color( var(--mainColor) blackness(+20%) ); } @media (--mobile) { .post-article :--heading { margin-top: 0; } }
Or if you like the Sass syntax, you could use PreCSS plugin pack:
@define-mixin social-icon $network $color { &.is-$network { background: $color; } } .social-icon { @mixin social-icon twitter #55acee; @mixin social-icon facebook #3b5998; padding: 10px 5px; @media (max-width: 640px) { padding: 0; } }
Features
Preprocessors are template languages, where you mix styles with code (like PHP does with HTML).
In contrast, in PostCSS you write a custom subset of CSS. All code can only be in JS plugins.
As a result, PostCSS offers three main benefits:
- Performance: PostCSS, written in JS, is 3 times faster than libsass, which is written in C++.
- Future CSS: PostCSS plugins can read and rebuild an entire document, meaning that they can provide new language features. For example, cssnext transpiles the latest W3C drafts to current CSS syntax.
- New abilities: PostCSS plugins can read and change every part of CSS.
It makes many new classes of tools possible. Autoprefixer,
rtlcss,doiuseorpostcss-colorblindare good examples.
Usage
Start using PostCSS in just two steps:
- Add PostCSS to your build tool.
- Select plugins from the list below and add them to your PostCSS process.
There are plugins for Grunt, Gulp, webpack, Broccoli, Brunch and ENB.
gulp.task('css', function () { var postcss = require('gulp-postcss'); return gulp.src('src/**/*.css') .pipe( postcss([ require('cssnext')(), require('cssnano')() ]) ) .pipe( gulp.dest('build/') ); });
For other environments, you can use the CLI tool or the JS API:
var postcss = require('postcss'); postcss([ require('cssnext')(), require('cssnano')() ]) .process(css, { from: 'src/app.css', to: 'app.css' }) .then(function (result) { fs.writeFileSync('app.css', result.css); if ( result.map ) fs.writeFileSync('app.css.map', result.map); });
You can also use PostCSS plugins with Stylus by using poststylus.
Read the PostCSS API for more details about the JS API.
Plugins
Go to postcss.parts for a searchable catalog of the plugins mentioned below.
Control
There are two ways to make PostCSS magic more explicit.
Limit a plugin's local stylesheet context using postcss-plugin-context:
.css-example.is-test-for-css4-browsers { color: gray(255, 50%); } @context cssnext { .css-example.is-fallback-for-all-browsers { color: gray(255, 50%); } }
Or enable plugins directly in CSS using postcss-use:
@use autoprefixer(browsers: ['last 2 versions']); :fullscreen a { display: flex }
Packs
atcsscontains plugins that transform your CSS according to special annotation comments.cssnanocontains plugins that optimize CSS size for use in production.cssnextcontains plugins that allow you to use future CSS features today.precsscontains plugins that allow you to use Sass-like CSS.rucksackcontains plugins to speed up CSS development with new features and shortcuts.stylelintcontains plugins that lint your stylesheets.
Future CSS Syntax
postcss-color-functionsupports functions to transform colors.postcss-color-graysupports thegray()function.postcss-color-hex-alphasupports#rrggbbaaand#rgbanotation.postcss-color-hwbtransformshwb()to widely compatiblergb().postcss-color-rebeccapurplesupports therebeccapurplecolor.postcss-conic-gradientsupports theconic-gradientbackground.postcss-custom-mediasupports custom aliases for media queries.postcss-custom-propertiessupports variables, using syntax from the W3C Custom Properties.postcss-custom-selectorsadds custom aliases for selectors.postcss-extendsupports spec-approximate@extendfor rules and placeholders, recursively.postcss-font-varianttranspiles human-readablefont-variantto more widely supported CSS.postcss-hostmakes the Shadow DOM’s:hostselector work properly with pseudo-classes.postcss-media-minmaxadds<=and=>statements to media queries.postcss-pseudo-class-any-linkadds:any-linkpseudo-class.postcss-selector-nottransforms CSS4:not()to CSS3:not().mq4-hover-shimsupports the@media (hover)feature.
See also cssnext plugins pack to add future CSS syntax by one line of code.
Fallbacks
postcss-color-rgba-fallbacktransformsrgba()to hexadecimal.postcss-epubadds the-epub-prefix to relevant properties.postcss-opacityadds opacity filter for IE8.postcss-pseudoelementsConvert::selectors into:selectors for IE 8 compatibility.postcss-vmingeneratesvmfallback forvminunit in IE9.postcss-will-changeinserts 3D hack beforewill-changeproperty.autoprefixeradds vendor prefixes for you, using data from Can I Use.cssgraceprovides various helpers and transpiles CSS 3 for IE and other old browsers.pixremgenerates pixel fallbacks forremunits.
Language Extensions
postcss-bemadds at-rules for BEM and SUIT style classes.postcss-conditionalsadds@ifstatements.postcss-css-variablessupports variables for selectors, and at-rules using W3C similar syntax.postcss-define-propertyto define properties shortcut.postcss-eachadds@eachstatement.postcss-foradds@forloops.postcss-functionsenables exposure of JavaScript functions.postcss-local-constantsadds support for localized constants.postcss-mapenables configuration maps.postcss-mixinsenables mixins more powerful than Sass’, defined within stylesheets or in JS.postcss-media-variablesadds support forvar()andcalc()in@mediarulespostcss-modular-scaleadds a modular scalems()function.postcss-nestedunwraps nested rules.postcss-nested-propsunwraps nested properties.postcss-pseudo-class-entertransforms:enterinto:hoverand:focus.postcss-quantity-queriesenables quantity queries.postcss-sassy-mixinsenables mixins with Sass keywords.postcss-simple-extendlightweight extending of silent classes, like Sass’@extend.postcss-simple-varssupports for Sass-style variables.postcss-strip-unitsstrips units off of property values.postcss-vertical-rhythmadds a vertical rhythm unit based onfont-sizeandline-height.csstyleadds components workflow to your styles.
See also precss plugins pack to add them by one line of code.
Colors
postcss-brand-colorsinserts company brand colors in thebrand-colorsmodule.postcss-color-alphatransforms#hex.a,black(alpha)andwhite(alpha)torgba().postcss-color-hcltransformshcl(H, C, L)andhcl(H, C, L, alpha)to#rgbandrgba().postcss-color-hexatransformshexa(hex, alpha)intorgbaformat.postcss-color-mixmixes two colors together.postcss-color-palettetransforms CSS 2 color keywords to a custom palette.postcss-color-pantonetransforms pantone color to RGB.postcss-color-scaleadds a color scalecs()function.postcss-color-shortadds shorthand color declarations.postcss-colorblindtransforms colors using filters to simulate colorblindness.postcss-hexrgbaadds shorthand hexrgba(hex, alpha)method.
Images and Fonts
postcss-assetsallows you to simplify URLs, insert image dimensions, and inline files.postcss-at2xhandles retina background images via use ofat-2xkeyword.postcss-data-packermoves embedded Base64 data to a separate file.postcss-image-setaddsbackground-imagewith first image forimage-set().postcss-font-packsimplifies font declarations and validates they match configured font packs.postcss-fontpathadds font links for different browsers.postcss-spritesgenerates CSS sprites from stylesheets.postcss-svginsert inline SVG to CSS and allows to manage it colors.postcss-svg-fallbackconverts SVG in your CSS to PNG files for IE 8.postcss-svgoprocesses inline SVG through SVGO.postcss-urlrebases or inlinesurl()s.webpcssadds URLs for WebP images for browsers that support WebP.
Grids
postcss-gridadds a semantic grid system.postcss-neatis a semantic and fluid grid framework.lostfeature-richcalc()grid system by Jeet author.
Optimizations
postcss-calcreducescalc()to values (when expressions involve the same units).postcss-importinlines the stylesheets referred to by@importrules.postcss-single-charsetensures that there is one and only one@charsetrule at the top of file.postcss-zindexrebases positivez-indexvalues.css-byebyeremoves the CSS rules that you don’t want.css-mqpackerjoins matching CSS media queries into a single statement.stylehacksremoves CSS hacks based on browser support.
See also plugins in modular minifier cssnano.
Shortcuts
postcss-aliascreates shorter aliases for properties.postcss-all-link-colorsinsert colors for link-related pseudo-classes.postcss-borderadds shorthand for width and color of all borders inborderproperty.postcss-centercenters elements.postcss-circleinserts a circle with color.postcss-clearfixaddsfixandfix-legacyproperties to thecleardeclaration.postcss-cripshorthand properties for Crips that are too lazy to write.postcss-default-unitadds default unit to numeric CSS properties.postcss-easingsreplaces easing names from easings.net withcubic-bezier()functions.postcss-filteradds shorthand for black and white filter.postcss-focusadds:focusselector to every:hover.postcss-generate-presetallows quick generation of rules. Useful for creating repetitive utilities.postcss-positionadds shorthand declarations for position attributes.postcss-property-lookupallows referencing property values without a variable.postcss-responsive-typechangesfont-sizedepends on screen size.postcss-shortadds and extends numerous shorthand properties.postcss-sizeadds asizeshortcut that sets width and height with one declaration.postcss-transform-shortcutallows shorthand transform properties in CSS.postcss-trianglecreates a triangle.postcss-verthorzadds vertical and horizontal spacing declarations.font-magiciangenerates all the@font-facerules needed in CSS.
Others
postcss-class-prefixadds a prefix/namespace to class selectors.postcss-fakeidtransforms#fooIDs to attribute selectors[id="foo"].postcss-flexboxfixerunprefixes-webkit-only flexbox in legacy CSS.postcss-gradientfixerunprefixes-webkit-only gradients in legacy CSS.postcss-increase-specificityincreases the specificity of your selectors.postcss-mq-keyframesmoves any animation keyframes in media queries to the end of the file.postcss-pseudo-elements-contentautomatically addscontent: ""to:beforeand:after.postcss-pxtoremconverts pixel units torem.postcss-remove-prefixesremoves vendor prefixes.postcss-style-guidegenerates a style guide automatically.postcss-scopifyadds a user input scope to each selector.cssfmtformats CSS source code automatically inspired by Gofmt.perfectionistformats poorly written CSS and renders a “pretty” result.rtlcssmirrors styles for right-to-left locales.
Analysis
postcss-bem-linterlints CSS for conformance to SUIT CSS methodology.postcss-cssstatsreturns an object with CSS statistics.css2modernizrcreates a Modernizr config file that requires only the tests that your CSS uses.doiuselints CSS for browser support, using data from Can I Use.immutable-csslints CSS for class mutations.list-selectorslists and categorizes the selectors used in your CSS, for code review.
Reporters
postcss-browser-reporterdisplays warning messages from other plugins right in your browser.postcss-reporterlogs warnings and other messages from other plugins in the console.
Fun
postcss-australian-stylesheetsAustralian Style Sheets.postcss-canadian-stylesheetsCanadian Style Sheets.postcss-imperialadds CSS support for Imperial and US customary units of length.postcss-russian-unitsadds CSS support for russian units of length.postcss-pointerReplacespointer: cursorwithcursor: pointer.postcss-spiffinglets you use British English in your CSS.
How to Develop a PostCSS Plugin
Options
Source Map
PostCSS has great source maps support. It can read and interpret maps from previous transformation steps, autodetect the format that you expect, and output both external and inline maps.
To ensure that you generate an accurate source map, you must indicate the input
and output CSS file paths — using the options from and to, respectively.
To generate a new source map with the default options, simply set map: true.
This will generate an inline source map that contains the source content.
If you don’t want the map inlined, you can set map.inline: false.
processor .process(css, { from: 'app.sass.css', to: 'app.css', map: { inline: false }, }) .then(function (result) { result.map //=> '{ "version":3, // "file":"app.css", // "sources":["app.sass"], // "mappings":"AAAA,KAAI" }' });
If PostCSS finds source maps from a previous transformation, it will automatically update that source map with the same options.
If you want more control over source map generation, you can define the map
option as an object with the following parameters:
-
inlineboolean: indicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it istrue. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option.If you have an inline source map, the
result.mapproperty will be empty, as the source map will be contained within the text ofresult.css. -
prevstring, object or boolean: source map content from a previous processing step (for example, Sass compilation). PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually. If desired, you can omit the previous map withprev: false. -
sourcesContentboolean: indicates that PostCSS should set the origin content (for example, Sass source) of the source map. By default, it istrue. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option. -
annotationboolean or string: indicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments.By default, PostCSS presumes that you want to save the source map as
opts.to + '.map'and will use this path in the annotation comment. A different path can be set by providing a string value forannotation.If you have set
inline: true, annotation cannot be disabled.
Safe Mode
If you pass the safe: true option to the process or parse methods,
PostCSS will try to correct any syntax errors that it finds in the CSS.
postcss.parse('a {'); // will throw "Unclosed block" postcss.parse('a {', { safe: true }); // will return CSS root for a {}
This is useful for legacy code filled with hacks. Another use-case is interactive tools with live input — for example, the Autoprefixer demo.