README.md
PostCSS

PostCSS is a tool for transforming styles 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 | Syntaxes | Plugins | Development | 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 of the style transformations are performed by plugins, which are plain JS functions. Each plugin receives a CSS node tree, transforms it & then returns the 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 the 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 2 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 styles. It makes many new classes of tools possible. Autoprefixer, <code>rtlcss</code>, <code>doiuse</code> or <code>postcss-colorblind</code> are 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, ENB, Fly, Stylus, Duo and Connect/Express.
gulp.task('css', function () {
var postcss = require('gulp-postcss');
return gulp.src('src/**/*.css')
.pipe( postcss([ require('autoprefixer'), 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('autoprefixer'), 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);
});
If you want to run PostCSS on node.js 0.10, add Promise polyfill:
require('es6-promise').polyfill();
var postcss = require('postcss');
Read the PostCSS API for more details about the JS API.
Custom Syntaxes
PostCSS can transform styles in any syntax, not only in CSS.
There are 3 special arguments in process()
method to control syntax.
You can even separately set input parser and output stringifier.
syntax
accepts object withparse
andstringify
functions.parser
accepts input parser function.stringifier
accepts output stringifier function.
var safe = require('postcss-safe-parser');
postcss(plugins).process('a {', { parser: safe }).then(function (result) {
result.css //=> 'a {}'
});
Syntaxes
- <code>postcss-scss</code> to work with SCSS (but does not compile SCSS to CSS).
Parsers
- <code>postcss-safe-parser</code> finds and fix CSS syntax errors.
Stringifiers
- <code>midas</code> converts a CSS string to highlighted HTML.
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 <code>postcss-plugin-context</code>:
.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 <code>postcss-use</code>:
@use autoprefixer(browsers: ['last 2 versions']);
:fullscreen a {
display: flex
}
Packs
- <code>atcss</code> contains plugins that transform your CSS according to special annotation comments.
- <code>cssnano</code> contains plugins that optimize CSS size for use in production.
- <code>cssnext</code> contains plugins that allow you to use future CSS features today.
- <code>precss</code> contains plugins that allow you to use Sass-like CSS.
- <code>rucksack</code> contains plugins to speed up CSS development with new features and shortcuts.
- <code>short</code> adds and extends numerous shorthand properties.
- <code>stylelint</code> contains plugins that lint your stylesheets.
Future CSS Syntax
- <code>postcss-color-function</code> supports functions to transform colors.
- <code>postcss-color-gray</code> supports the
gray()
function. - <code>postcss-color-hex-alpha</code> supports
#rrggbbaa
and#rgba
notation. - <code>postcss-color-hwb</code> transforms
hwb()
to widely compatiblergb()
. - <code>postcss-color-rebeccapurple</code> supports the
rebeccapurple
color. - <code>postcss-conic-gradient</code> supports the
conic-gradient
background. - <code>postcss-custom-media</code> supports custom aliases for media queries.
- <code>postcss-custom-properties</code> supports variables, using syntax from the W3C Custom Properties.
- <code>postcss-custom-selectors</code> adds custom aliases for selectors.
- <code>postcss-extend</code> supports spec-approximate
@extend
for rules and placeholders, recursively. - <code>postcss-font-variant</code> transpiles human-readable
font-variant
to more widely supported CSS. - <code>postcss-host</code> makes the Shadow DOM’s
:host
selector work properly with pseudo-classes. - <code>postcss-initial</code> supports
initial
keyword andall: initial
to clean inherit styles. - <code>postcss-media-minmax</code> adds
<=
and=>
statements to media queries. - <code>postcss-pseudo-class-any-link</code> adds
:any-link
pseudo-class. - <code>postcss-selector-not</code> transforms CSS4
:not()
to CSS3:not()
. - <code>postcss-selector-matches</code> transforms CSS4
:matches()
to more compatible CSS. - <code>postcss-apply</code> supports custom properties sets references
- <code>mq4-hover-shim</code> supports the
@media (hover)
feature.
See also <code>cssnext</code> plugins pack to add future CSS syntax by one line of code.
Fallbacks
- <code>postcss-color-rgba-fallback</code> transforms
rgba()
to hexadecimal. - <code>postcss-epub</code> adds the
-epub-
prefix to relevant properties. - <code>postcss-mqwidth-to-class</code> converts min/max-width media queries to classes.
- <code>postcss-opacity</code> adds opacity filter for IE8.
- <code>postcss-pseudoelements</code> Convert
::
selectors into:
selectors for IE 8 compatibility. - <code>postcss-unmq</code> removes media queries while preserving desktop rules for IE≤8.
- <code>postcss-vmin</code> generates
vm
fallback forvmin
unit in IE9. - <code>postcss-will-change</code> inserts 3D hack before
will-change
property. - <code>autoprefixer</code> adds vendor prefixes for you, using data from Can I Use.
- <code>cssgrace</code> provides various helpers and transpiles CSS 3 for IE and other old browsers.
- <code>pixrem</code> generates pixel fallbacks for
rem
units. - <code>postcss-round-subpixels</code> plugin that rounds sub-pixel values to the nearest full pixel.
Language Extensions
- <code>postcss-atroot</code> place rules directly at the root node.
- <code>postcss-bem</code> adds at-rules for BEM and SUIT style classes.
- <code>postcss-conditionals</code> adds
@if
statements. - <code>postcss-css-variables</code> supports variables for selectors, and at-rules using W3C similar syntax.
- <code>postcss-define-property</code> to define properties shortcut.
- <code>postcss-each</code> adds
@each
statement. - <code>postcss-for</code> adds
@for
loops. - <code>postcss-functions</code> enables exposure of JavaScript functions.
- <code>postcss-local-constants</code> adds support for localized constants.
- <code>postcss-map</code> enables configuration maps.
- <code>postcss-match</code> adds
@match
for Rust-style pattern matching. - <code>postcss-mixins</code> enables mixins more powerful than Sass’, defined within stylesheets or in JS.
- <code>postcss-media-variables</code> adds support for
var()
andcalc()
in@media
rules - <code>postcss-modular-scale</code> adds a modular scale
ms()
function. - <code>postcss-nested</code> unwraps nested rules.
- <code>postcss-nested-props</code> unwraps nested properties.
- <code>postcss-nested-vars</code> supports nested Sass-style variables.
- <code>postcss-pseudo-class-enter</code> transforms
:enter
into:hover
and:focus
. - <code>postcss-quantity-queries</code> enables quantity queries.
- <code>postcss-sassy-mixins</code> enables mixins with Sass keywords.
- <code>postcss-simple-extend</code> lightweight extending of silent classes,
like Sass’
@extend
. - <code>postcss-simple-vars</code> supports for Sass-style variables.
- <code>postcss-strip-units</code> strips units off of property values.
- <code>postcss-vertical-rhythm</code> adds a vertical rhythm unit
based on
font-size
andline-height
. - <code>csstyle</code> adds components workflow to your styles.
See also <code>precss</code> plugins pack to add them by one line of code.
Colors
- <code>postcss-ase-colors</code> replaces color names with values read from an ASE palette file.
- <code>postcss-brand-colors</code> inserts company brand colors
in the
brand-colors
module. - <code>postcss-color-alpha</code> transforms
#hex.a
,black(alpha)
andwhite(alpha)
torgba()
. - <code>postcss-color-hcl</code> transforms
hcl(H, C, L)
andhcl(H, C, L, alpha)
to#rgb
andrgba()
. - <code>postcss-color-hexa</code> transforms
hexa(hex, alpha)
intorgba
format. - <code>postcss-color-mix</code> mixes two colors together.
- <code>postcss-color-palette</code> transforms CSS 2 color keywords to a custom palette.
- <code>postcss-color-pantone</code> transforms pantone color to RGB.
- <code>postcss-color-scale</code> adds a color scale
cs()
function. - <code>postcss-color-short</code> adds shorthand color declarations.
- <code>postcss-colorblind</code> transforms colors using filters to simulate colorblindness.
- <code>postcss-hexrgba</code> adds shorthand hex
rgba(hex, alpha)
method. - <code>postcss-rgb-plz</code> converts 3 or 6 digit hex values to
rgb
. - <code>colorguard</code> helps maintain a consistent color palette.
Images and Fonts
- <code>postcss-assets</code> allows you to simplify URLs, insert image dimensions, and inline files.
- <code>postcss-at2x</code> handles retina background images via use of
at-2x
keyword. - <code>postcss-copy-assets</code> copies assets referenced by relative
url()
s into a build directory. - <code>postcss-data-packer</code> moves embedded Base64 data to a separate file.
- <code>postcss-image-set</code> adds
background-image
with first image forimage-set()
. - <code>postcss-image-inliner</code> inlines local and remote images.
- <code>postcss-instagram</code> adds Instagram filters to
filter
. - <code>postcss-font-pack</code> simplifies font declarations and validates they match configured font packs.
- <code>postcss-fontpath</code> adds font links for different browsers.
- <code>postcss-responsive-images</code> adds stylesheets for making your images responsive
- <code>postcss-sprites</code> generates CSS sprites from stylesheets.
- <code>postcss-svg</code> insert inline SVG to CSS and allows to manage it colors.
- <code>postcss-svg-fallback</code> converts SVG in your CSS to PNG files for IE 8.
- <code>postcss-svgo</code> processes inline SVG through SVGO.
- <code>postcss-url</code> rebases or inlines
url()
s. - <code>postcss-urlrev</code> adds MD5 hash strings to
url()
s. - <code>postcss-write-svg</code> write inline SVGs in CSS.
- <code>webpcss</code> adds URLs for WebP images for browsers that support WebP.
Grids
- <code>postcss-grid</code> adds a semantic grid system.
- <code>postcss-simple-grid</code> create grid with one line.
- <code>postcss-neat</code> is a semantic and fluid grid framework.
- <code>lost</code> feature-rich
calc()
grid system by Jeet author.
Optimizations
- <code>postcss-calc</code> reduces
calc()
to values (when expressions involve the same units). - <code>postcss-import</code> inlines the stylesheets referred to by
@import
rules. - <code>postcss-partial-import</code> inlines standard imports and Sass-like partials.
- <code>postcss-single-charset</code> ensures that there is one and only one
@charset
rule at the top of file. - <code>postcss-zindex</code> rebases positive
z-index
values. - <code>css-byebye</code> removes the CSS rules that you don’t want.
- <code>css-mqpacker</code> joins matching CSS media queries into a single statement.
- <code>stylehacks</code> removes CSS hacks based on browser support.
See also plugins in modular minifier <code>cssnano</code>.
Shortcuts
- <code>postcss-alias</code> creates shorter aliases for properties.
- <code>postcss-alias-atrules</code> creates shorter aliases for at-rules.
- <code>postcss-all-link-colors</code> insert colors for link-related pseudo-classes.
- <code>postcss-border</code> adds shorthand for width and color of all borders
in
border
property. - <code>postcss-center</code> centers elements.
- <code>postcss-circle</code> inserts a circle with color.
- <code>postcss-clearfix</code> adds
fix
andfix-legacy
properties to theclear
declaration. - <code>postcss-crip</code> shorthand properties for Crips that are too lazy to write.
- <code>postcss-default-unit</code> adds default unit to numeric CSS properties.
- <code>postcss-easings</code> replaces easing names from easings.net
with
cubic-bezier()
functions. - <code>postcss-filter</code> adds shorthand for black and white filter.
- <code>postcss-focus</code> adds
:focus
selector to every:hover
. - <code>postcss-generate-preset</code> allows quick generation of rules. Useful for creating repetitive utilities.
- <code>postcss-input-style</code> adds new pseudo-elements for cross-browser styling of inputs.
- <code>postcss-position</code> adds shorthand declarations for position attributes.
- <code>postcss-property-lookup</code> allows referencing property values without a variable.
- <code>postcss-responsive-type</code> changes
font-size
depends on screen size. - <code>postcss-size</code> adds a
size
shortcut that sets width and height with one declaration. - <code>postcss-transform-shortcut</code> allows shorthand transform properties in CSS.
- <code>postcss-triangle</code> creates a triangle.
- <code>postcss-verthorz</code> adds vertical and horizontal spacing declarations.
- <code>font-magician</code> generates all the
@font-face
rules needed in CSS.
Others
- <code>postcss-autoreset</code> automatically adds reset styles.
- <code>postcss-class-prefix</code> adds a prefix/namespace to class selectors.
- <code>postcss-currency</code> replaces name of currency with symbols.
- <code>postcss-fakeid</code> transforms
#foo
IDs to attribute selectors[id="foo"]
. - <code>postcss-flexboxfixer</code> unprefixes
-webkit-
only flexbox in legacy CSS. - <code>postcss-flexbugs-fixes</code> fixes some of known flexbox bugs.
- <code>postcss-gradientfixer</code> unprefixes
-webkit-
only gradients in legacy CSS. - <code>postcss-increase-specificity</code> increases the specificity of your selectors.
- <code>postcss-mq-keyframes</code> moves any animation keyframes in media queries to the end of the file.
- <code>postcss-pseudo-elements-content</code> adds
content: ''
to:before-c
and:after-c
. - <code>postcss-pseudo-content-insert</code> adds
content: ''
to:before
and:after
if it is missing. - <code>postcss-pxtorem</code> converts pixel units to
rem
. - <code>postcss-remove-prefixes</code> removes vendor prefixes.
- <code>postcss-style-guide</code> generates a style guide automatically.
- <code>postcss-scopify</code> adds a user input scope to each selector.
- <code>cssfmt</code> formats CSS source code automatically inspired by Gofmt.
- <code>perfectionist</code> formats poorly written CSS and renders a “pretty” result.
- <code>rtlcss</code> mirrors styles for right-to-left locales.
Analysis
- <code>postcss-bem-linter</code> lints CSS for conformance to SUIT CSS methodology.
- <code>postcss-cssstats</code> returns an object with CSS statistics.
- <code>css2modernizr</code> creates a Modernizr config file that requires only the tests that your CSS uses.
- <code>doiuse</code> lints CSS for browser support, using data from Can I Use.
- <code>immutable-css</code> lints CSS for class mutations.
- <code>list-selectors</code> lists and categorizes the selectors used in your CSS, for code review.
Reporters
- <code>postcss-browser-reporter</code> displays warning messages from other plugins right in your browser.
- <code>postcss-reporter</code> logs warnings and other messages from other plugins in the console.
Fun
- <code>postcss-australian-stylesheets</code> Australian Style Sheets.
- <code>postcss-canadian-stylesheets</code> Canadian Style Sheets.
- <code>postcss-german-stylesheets</code> German Style Sheets.
- <code>postcss-russian-stylesheets</code> Russian Style Sheets.
- <code>postcss-swedish-stylesheets</code> Swedish Style Sheets.
- <code>postcss-tatar-stylesheets</code> Tatar Style Sheets
- <code>postcss-lolcat-stylesheets</code> Lolspeak Style Sheets.
- <code>postcss-imperial</code> adds CSS support for Imperial and US customary units of length.
- <code>postcss-russian-units</code> adds CSS support for russian units of length.
- <code>postcss-pointer</code> Replaces
pointer: cursor
withcursor: pointer
. - <code>postcss-spiffing</code> lets you use British English in your CSS.
How to Develop for PostCSS
Syntax
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:
inline
boolean: 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.map
property will be empty,
as the source map will be contained within the text of result.css
.
prev
string, 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
.sourcesContent
boolean: 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.annotation
boolean 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 for annotation
.
If you have set inline: true
, annotation cannot be disabled.