![New axobject-query Maintainer Faces Backlash Over Controversial Decision to Support Legacy Node.js Versions](https://cdn.sanity.io/images/cgdhsj6q/production/86e6ebdea652d20da070ebbda20134b839972db7-1024x1024.webp?w=800&fit=max&auto=format)
Security News
New axobject-query Maintainer Faces Backlash Over Controversial Decision to Support Legacy Node.js Versions
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.
postcss
Advanced tools
Package description
PostCSS is a tool for transforming CSS with JavaScript plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more.
Autoprefixing
Automatically adds vendor prefixes to CSS rules using values from Can I Use. It is recommended by Google and used in Twitter and Alibaba.
postcss([ require('autoprefixer') ]).process(css).then(result => { result.warnings().forEach(warn => { console.warn(warn.toString()); }); console.log(result.css); });
CSS Variables
Transforms CSS Custom Properties (CSS variables) syntax into a static representation that can be understood by browsers that do not support this feature.
postcss([ require('postcss-custom-properties') ]).process(css).then(result => { console.log(result.css); });
CSS Nesting
Allows you to nest one style rule inside another, following the CSS Nesting Module Level 3 specification.
postcss([ require('postcss-nesting') ]).process(css).then(result => { console.log(result.css); });
Minification
A modular minifier, built on top of the PostCSS ecosystem. It is used to minimize CSS for better performance.
postcss([ require('cssnano') ]).process(css).then(result => { console.log(result.css); });
Future CSS Syntax
Allows you to use future CSS features today. It polyfills CSS features that are not yet fully supported in browsers.
postcss([ require('postcss-preset-env') ]).process(css).then(result => { console.log(result.css); });
Sass is a mature, stable, and powerful professional grade CSS extension language. It provides mechanisms such as variables, nesting, and mixins, which are not present in standard CSS. Unlike PostCSS, which uses JavaScript plugins, Sass has its own syntax and compiles to standard CSS.
Less is a backward-compatible language extension for CSS. It also allows variables, mixins, functions and many other techniques that allow you to make CSS more maintainable and extendable. Less is similar to Sass and differs from PostCSS in that it offers a different syntax and set of features.
Stylus is a preprocessor that serves as a more robust and feature-rich alternative to CSS. It supports both an indented syntax and regular CSS style. Stylus provides significant flexibility and feature parity with Sass and Less but with a different syntax and feature set compared to PostCSS.
Changelog
4.1.10
plugin
field in CssSyntaxError
.Readme
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 Google, Twitter, Alibaba, and Shopify. Its plugin, Autoprefixer, 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. Weibo account: postcss. VK.com page: postcss.
Examples | Features | Usage | Plugins | Write Own Plugin | 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 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 combine
postcss-nested
and postcss-mixins
:
@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:
rtlcss
,
doiuse
or postcss-colorblind
are good examples.You just need to follow these two steps to use PostCSS:
There are plugins for Grunt, Gulp, webpack, Broccoli and Brunch.
gulp.task('css', function () {
var postcss = require('gulp-postcss');
return gulp.src('src/**/*.css')
.pipe( postcss([ require('cssnext'), require('cssgrace') ]) )
.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('cssgrace') ])
.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);
});
Read the PostCSS API for more details about the JS API.
With postcss-plugin-context
you can run different plugins
on different parts of CSS.
.css-example.is-test-for-css4-browsers {
color: gray(255, 50%);
}
@context cssnext {
.css-example.is-fallback-for-all-browsers {
color: gray(255, 50%);
}
}
cssnano
contains plugins that optimise CSS size for use in production.cssnext
contains plugins that allow you to use future CSS features today.atcss
contains plugins that transform your CSS according
to special annotation comments.postcss-color-function
supports functions to transform colors.postcss-color-gray
supports the gray()
function.postcss-color-hex-alpha
supports #rrggbbaa
and #rgba
notation.postcss-color-hwb
transforms hwb()
to widely compatible rgb()
.postcss-color-rebeccapurple
supports the rebeccapurple
color.postcss-custom-media
supports custom aliases for media queries.postcss-custom-properties
supports variables, using syntax from
the W3C Custom Properties.postcss-css-variables
supports variables for descendant/nested rules and at-rulespostcss-custom-selectors
adds custom aliases for selectors.postcss-font-variant
transpiles human-readable font-variant
to more
widely supported CSS.postcss-host
makes the Shadow DOM’s :host
selector work properly
with pseudo-classes.postcss-media-minmax
adds <=
and =>
statements to media queries.postcss-selector-not
transforms CSS4 :not()
to CSS3 :not()
.mq4-hover-shim
supports the @media (hover)
feature.postcss-color-rgba-fallback
transforms rgba()
to hexadecimal.postcss-epub
adds the -epub-
prefix to relevant properties.postcss-image-set
adds background-image
with first image for image-set()
postcss-opacity
adds opacity filter for IE8.postcss-pseudoelements
Convert ::
selectors into :
selectors
for IE 8 compatibility.postcss-vmin
generates vm
fallback for vmin
unit in IE9.postcss-will-change
inserts 3D hack before will-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 for rem
units.postcss-color-alpha
transforms #hex.a
, black(alpha)
and white(alpha)
to rgba()
.postcss-for
adds @for
loops.postcss-conditionals
adds @if
statements.postcss-mixins
enables mixins more powerful than Sass’s,
defined within stylesheets or in JS.postcss-map
enables configuration maps.postcss-neat
is a semantic and fluid grid framework.postcss-nested
unwraps nested rules.postcss-quantity-queries
enables quantity queries.postcss-simple-extend
supports extending of silent classes,
like Sass’s @extend
.postcss-simple-vars
supports for Sass-style variables.csstyle
adds components workflow to your styles.lost
feature rich calc()
grid system by Jeet author.postcss-assets
allows you to simplify URLs, insert image dimensions,
and inline files.postcss-at2x
handles retina background images via use of at-2x
keyword.postcss-calc
reduces calc()
to values
(when expressions involve the same units).postcss-colormin
reduces color values to their smallest representations.postcss-convert-values
reduces length and time values (e.g. ms -> s).postcss-data-packer
moves embedded Base64 data out of the stylesheet
and into a separate file.postcss-discard-duplicates
removes duplicate declarations and rules.postcss-discard-empty
removes empty rules and declarations.postcss-discard-font-face
removes unused @font-face
declarations.postcss-font-family
optimises font
and font-family
declarations.postcss-import
inlines the stylesheets referred to by @import
rules.postcss-merge-idents
merges duplicated @keyframes
with different names.postcss-merge-rules
merges adjacent rules when
selectors/properties overlap.postcss-minify-font-weight
compresses font-weight
values.postcss-minify-selectors
normalizes selectors for better compression.postcss-normalize-url
normalizes url()
s and trims quotes
where they are unnecessary.postcss-reduce-idents
compresses @keyframes
, @counter-style
&
counter
identifiers.postcss-url
rebases or inlines url()
s.postcss-zindex
rebases positive z-index
values.csswring
is a CSS minifier.css-byebye
removes the CSS rules that you don’t want.css-mqpacker
joins matching CSS media queries into a single statement.webpcss
adds URLs for WebP images, so they can be used by browsers
that support WebP.postcss-single-charset
ensures that there is one
and only one @charset
rule at the top of file.postcss-default-unit
adds default unit to numeric CSS properties.postcss-easings
replaces easing names from easings.net
with cubic-bezier()
functions.postcss-focus
adds :focus
selector to every :hover
.postcss-generate-preset
allows quick generation of rules. Useful for creating repetitive utilities.postcss-size
adds a size
shortcut that sets width and height
with one declaration.postcss-brand-colors
inserts company brand colors
in the brand-colors
module.postcss-color-palette
transforms CSS 2 color keywords to a custom palette.postcss-colorblind
transforms colors using filters to simulate
colorblindnesspostcss-discard-comments
removes comments based on rules you specify.postcss-log-warnings
logs warnings messages from other plugins
in the console.postcss-messages
displays warning messages from other plugins
right in your browser.postcss-pxtorem
convert pixel units to rem
.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.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.list-selectors
lists and categorizes the selectors used in your CSS,
for code review.postcss-australian-stylesheets
Australian Style Sheets.postcss-canadian-stylesheets
Canadian Style Sheets.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 files 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 use 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 is true
.
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
with prev: false
.
sourcesContent
boolean: indicates that PostCSS should set the origin
content (for example, Sass source) of the source map. By default it is true
.
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. But if the input CSS does not have any annotation
comment, PostCSS will omit it, too, even if you do not set this option.
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.
But you can set another path by providing a string value for annotation
.
If you have set inline: true
, annotation cannot be disabled.
If you provide a 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.
FAQs
Tool for transforming styles with JS plugins
The npm package postcss receives a total of 41,930,369 weekly downloads. As such, postcss popularity was classified as popular.
We found that postcss demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.
Security News
Results from the 2023 State of JavaScript Survey highlight key trends, including Vite's dominance, rising TypeScript adoption, and the enduring popularity of React. Discover more insights on developer preferences and technology usage.
Security News
The US Justice Department has penalized two consulting firms $11.3 million for failing to meet cybersecurity requirements on federally funded projects, emphasizing strict enforcement to protect sensitive government data.