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.
Support / Discussion: gitter.
Examples | Features | Usage | Syntaxes | Plugins | Development | Options |
---|
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;
}
}
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,
rtlcss
,doiuse
orpostcss-colorblind
are good examples.
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/') );
});
There is postcss-js to use PostCSS plugins in React Inline Styles, Free Style, Radium and other CSS-in-JS solutions.
To process CSS within the <style>
tags and inline style=
attributes
in your HTML consider using html-postcss and gulp-html-postcss.
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.
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 {}'
});
postcss-scss
to work with SCSS (but does not compile SCSS to CSS).
postcss-safe-parser
finds and fix CSS syntax errors.
midas
converts a CSS string to highlighted HTML.
Go to postcss.parts for a searchable catalog of the plugins mentioned below.
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
}
atcss
contains plugins that transform your CSS according to special annotation comments.cssnano
contains plugins that optimize CSS size for use in production.cssnext
contains plugins that allow you to use future CSS features today.oldie
contains plugins that transform your CSS for older Internet Explorer compatibility.precss
contains plugins that allow you to use Sass-like CSS.rucksack
contains plugins to speed up CSS development with new features and shortcuts.short
adds and extends numerous shorthand properties.stylelint
contains plugins that lint your stylesheets.
postcss-color-function
supports functions to transform colors.postcss-color-gray
supports thegray()
function.postcss-color-hex-alpha
supports#rrggbbaa
and#rgba
notation.postcss-color-hwb
transformshwb()
to widely compatiblergb()
.postcss-color-rebeccapurple
supports therebeccapurple
color.postcss-conic-gradient
supports theconic-gradient
background.postcss-custom-media
supports custom aliases for media queries.postcss-custom-properties
supports variables, using syntax from the W3C Custom Properties.postcss-custom-selectors
adds custom aliases for selectors.postcss-extend
supports spec-approximate@extend
for rules and placeholders, recursively.postcss-font-variant
transpiles human-readablefont-variant
to more widely supported CSS.postcss-host
makes the Shadow DOM’s:host
selector work properly with pseudo-classes.postcss-initial
supportsinitial
keyword andall: initial
to clean inherit styles.postcss-media-minmax
adds<=
and=>
statements to media queries.postcss-pseudo-class-any-link
adds:any-link
pseudo-class.postcss-selector-not
transforms CSS4:not()
to CSS3:not()
.postcss-selector-matches
transforms CSS4:matches()
to more compatible CSS.postcss-apply
supports custom properties sets referencesmq4-hover-shim
supports the@media (hover)
feature.
See also cssnext
plugins pack to add future CSS syntax by one line of code.
postcss-color-rgba-fallback
transformsrgba()
to hexadecimal.postcss-epub
adds the-epub-
prefix to relevant properties.postcss-fallback
addsfallback
function to avoid duplicate declarations.postcss-mqwidth-to-class
converts min/max-width media queries to classes.postcss-opacity
adds opacity filter for IE8.postcss-pseudoelements
Convert::
selectors into:
selectors for IE 8 compatibility.postcss-round-subpixels
plugin that rounds sub-pixel values to the nearest full pixel.postcss-unmq
removes media queries while preserving desktop rules for IE≤8.postcss-vmin
generatesvm
fallback forvmin
unit in IE9.postcss-will-change
inserts 3D hack beforewill-change
property.autoprefixer
adds vendor prefixes for you, using data from Can I Use.cssgrace
provides various helpers and transpiles CSS 3 for IE and other old browsers.pixrem
generates pixel fallbacks forrem
units.
See also oldie
plugins pack.
postcss-atroot
place rules directly at the root node.postcss-bem
adds at-rules for BEM and SUIT style classes.postcss-conditionals
adds@if
statements.postcss-css-variables
supports variables for selectors, and at-rules using W3C similar syntax.postcss-define-property
to define properties shortcut.postcss-each
adds@each
statement.postcss-for
adds@for
loops.postcss-at-rules-variables
adds support for custom properties in@for
,@each
,@if
, etc.postcss-functions
enables exposure of JavaScript functions.postcss-local-constants
adds support for localized constants.postcss-map
enables configuration maps.postcss-match
adds@match
for Rust-style pattern matching.postcss-mixins
enables mixins more powerful than Sass’, defined within stylesheets or in JS.postcss-media-variables
adds support forvar()
andcalc()
in@media
rulespostcss-modular-scale
adds a modular scalems()
function.postcss-nested
unwraps nested rules.postcss-nested-props
unwraps nested properties.postcss-nested-vars
supports nested Sass-style variables.postcss-pseudo-class-enter
transforms:enter
into:hover
and:focus
.postcss-quantity-queries
enables quantity queries.postcss-reverse-media
reverse/Invert media query parameters.postcss-sassy-mixins
enables mixins with Sass keywords.postcss-simple-extend
lightweight extending of silent classes, like Sass’@extend
.postcss-simple-vars
supports for Sass-style variables.postcss-strip-units
strips units off of property values.postcss-vertical-rhythm
adds a vertical rhythm unit based onfont-size
andline-height
.csstyle
adds components workflow to your styles.
See also precss
plugins pack to add them by one line of code.
postcss-ase-colors
replaces color names with values read from an ASE palette file.postcss-brand-colors
inserts company brand colors in thebrand-colors
module.postcss-color-alpha
transforms#hex.a
,black(alpha)
andwhite(alpha)
torgba()
.postcss-color-hcl
transformshcl(H, C, L)
andhcl(H, C, L, alpha)
to#rgb
andrgba()
.postcss-color-hexa
transformshexa(hex, alpha)
intorgba
format.postcss-color-mix
mixes two colors together.postcss-color-palette
transforms CSS 2 color keywords to a custom palette.postcss-color-pantone
transforms pantone color to RGB.postcss-color-scale
adds a color scalecs()
function.postcss-color-short
adds shorthand color declarations.postcss-color-yiq
sets foreground colors using the YIQ color space.postcss-colorblind
transforms colors using filters to simulate colorblindness.postcss-contrast
checks background-color and gives either white or black.postcss-hexrgba
adds shorthand hexrgba(hex, alpha)
method.postcss-rgb-plz
converts 3 or 6 digit hex values torgb
.colorguard
helps maintain a consistent color palette.
postcss-assets
allows you to simplify URLs, insert image dimensions, and inline files.postcss-assets-rebase
rebases assets fromurl()
.postcss-at2x
handles retina background images via use ofat-2x
keyword.postcss-copy-assets
copies assets referenced by relativeurl()
s into a build directory.postcss-data-packer
moves embedded Base64 data to a separate file.postcss-image-set
addsbackground-image
with first image forimage-set()
.postcss-image-inliner
inlines local and remote images.postcss-instagram
adds Instagram filters tofilter
.postcss-font-pack
simplifies font declarations and validates they match configured font packs.postcss-fontpath
adds font links for different browsers.postcss-responsive-images
adds stylesheets for making your images responsive.postcss-sprites
generates CSS sprites from stylesheets.postcss-svg
insert inline SVG to CSS and allows to manage it colors.postcss-svg-fallback
converts SVG in your CSS to PNG files for IE 8.postcss-svgo
processes inline SVG through SVGO.postcss-url
rebases or inlinesurl()
s.postcss-urlrev
adds MD5 hash strings tourl()
s.postcss-write-svg
write inline SVGs in CSS.webpcss
adds URLs for WebP images for browsers that support WebP.
postcss-grid
adds a semantic grid system.postcss-simple-grid
create grid with one line.postcss-neat
is a semantic and fluid grid framework.lost
feature-richcalc()
grid system by Jeet author.
postcss-calc
reducescalc()
to values (when expressions involve the same units).postcss-import
inlines the stylesheets referred to by@import
rules.postcss-partial-import
inlines standard imports and Sass-like partials.postcss-single-charset
ensures that there is one and only one@charset
rule at the top of file.postcss-zindex
rebases positivez-index
values.css-byebye
removes the CSS rules that you don’t want.css-mqpacker
joins matching CSS media queries into a single statement.stylehacks
removes CSS hacks based on browser support.
See also plugins in modular minifier cssnano
.
postcss-alias
creates shorter aliases for properties.postcss-alias-atrules
creates shorter aliases for at-rules.postcss-all-link-colors
insert colors for link-related pseudo-classes.postcss-border
adds shorthand for width and color of all borders inborder
property.postcss-center
centers elements.postcss-circle
inserts a circle with color.postcss-clearfix
addsfix
andfix-legacy
properties to theclear
declaration.postcss-crip
shorthand properties for Crips that are too lazy to write.postcss-default-unit
adds default unit to numeric CSS properties.postcss-easings
replaces easing names from easings.net withcubic-bezier()
functions.postcss-filter
adds shorthand for black and white filter.postcss-focus
adds:focus
selector to every:hover
.postcss-generate-preset
allows quick generation of rules. Useful for creating repetitive utilities.postcss-input-style
adds new pseudo-elements for cross-browser styling of inputs.postcss-position
adds shorthand declarations for position attributes.postcss-property-lookup
allows referencing property values without a variable.postcss-responsive-type
changesfont-size
depends on screen size.postcss-short-font-size
extendsfont-size
to define line-height as a second value.postcss-short-position
extendsposition
to define edges as additional values.postcss-short-spacing
extendsmargin
andpadding
to allow for omitted edges.postcss-short-text
adds atext
shortcut property for several text-related properties.postcss-size
adds asize
shortcut that sets width and height with one declaration.postcss-transform-shortcut
allows shorthand transform properties in CSS.postcss-triangle
creates a triangle.postcss-verthorz
adds vertical and horizontal spacing declarations.font-magician
generates all the@font-face
rules needed in CSS.
postcss-autoreset
automatically adds reset styles.postcss-class-prefix
adds a prefix/namespace to class selectors.postcss-currency
replaces name of currency with symbols.postcss-fakeid
transforms#foo
IDs to attribute selectors[id="foo"]
.postcss-flexboxfixer
unprefixes-webkit-
only flexbox in legacy CSS.postcss-flexbugs-fixes
fixes some of known flexbox bugs.postcss-gradientfixer
unprefixes-webkit-
only gradients in legacy CSS.postcss-increase-specificity
increases the specificity of your selectors.postcss-mq-keyframes
moves any animation keyframes in media queries to the end of the file.postcss-pseudo-elements-content
addscontent: ''
to:before-c
and:after-c
.postcss-pseudo-content-insert
addscontent: ''
to:before
and:after
if it is missing.postcss-pxtorem
converts pixel units torem
.postcss-select
select rules based off a selector list.postcss-shorthand-expand
expands shorthand properties.postcss-remove-prefixes
removes vendor prefixes.postcss-style-guide
generates a style guide automatically.postcss-scopify
adds a user input scope to each selector.cssfmt
formats CSS source code automatically inspired by Gofmt.perfectionist
formats poorly written CSS and renders a “pretty” result.rtlcss
mirrors styles for right-to-left locales.
postcss-bem-linter
lints CSS for conformance to SUIT CSS methodology.postcss-cssstats
returns an object with CSS statistics.postcss-regexp-detect
search for regexp in CSS declarations.css2modernizr
creates a Modernizr config file that requires only the tests that your CSS uses.doiuse
lints CSS for browser support, using data from Can I Use.immutable-css
lints CSS for class mutations.list-selectors
lists and categorizes the selectors used in your CSS, for code review.
postcss-browser-reporter
displays warning messages from other plugins right in your browser.postcss-reporter
logs warnings and other messages from other plugins in the console.
postcss-australian-stylesheets
Australian Style Sheets.postcss-canadian-stylesheets
Canadian Style Sheets.postcss-german-stylesheets
German Style Sheets.postcss-russian-stylesheets
Russian Style Sheets.postcss-swedish-stylesheets
Swedish Style Sheets.postcss-tatar-stylesheets
Tatar Style Sheetspostcss-lolcat-stylesheets
Lolspeak Style Sheets.postcss-imperial
adds CSS support for Imperial and US customary units of length.postcss-russian-units
adds CSS support for russian units of length.postcss-pointer
Replacespointer: cursor
withcursor: pointer
.postcss-spiffing
lets you use British English in your CSS.
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 ofresult.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 forannotation
.If you have set
inline: true
, annotation cannot be disabled.