Git Product home page Git Product logo

postcss's Introduction

PostCSS Travis Build Status AppVeyor Build Status Gitter

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
Sponsored by Evil Martians

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, has same performance as 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 or postcss-colorblind are good examples.

Usage

Start using PostCSS in just two steps:

  1. Add PostCSS to your build tool.
  2. Select plugins from the list below and add them to your PostCSS process.

There are plugins for Grunt, Gulp, webpackBroccoli, Brunch, ENB, Fly, Stylus, Meteor, 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] or [posthtml-postcss] plugin.

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 with parse and stringify 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-js to React Inline Styles, Radium, Free Style and other CSS-in-JS.
  • postcss-safe-parser finds and fix CSS syntax errors.
  • midas 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 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

  • 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.
  • level4 contains only plugins that let you write CSS4 without the IE9 fallbacks.
  • short adds and extends numerous shorthand properties.
  • stylelint contains plugins that lint your stylesheets.

Future CSS Syntax

See also cssnext plugins pack to add future CSS syntax by one line of code.

Fallbacks

See also oldie plugins pack.

Language Extensions

See also precss plugins pack to add them by one line of code.

Colors

Images and Fonts

Grids

Optimizations

See also plugins in modular minifier cssnano.

Shortcuts

Others

Analysis

Reporters

Fun

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 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. 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.

postcss's People

Contributors

ai avatar ben-eb avatar davidtheclark avatar moox avatar jednano avatar jonathantneal avatar trysound avatar madlittlemods avatar mohammadyounes avatar johno avatar lydell avatar andyjansson avatar masaakim avatar andrepolischuk avatar simonsmith avatar roman-vanesyan avatar maximkoretskiy avatar cvrebert avatar pascalduez avatar wolfgangkluge avatar philip-peterson avatar yuezk avatar semigradsky avatar azat-io avatar zhouwenbin avatar pazams avatar antyakushev avatar iamstarkov avatar justim avatar termina1 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.