PostCSS Plugins
控制
有两个办法让 PostCSS 的魔法更加直观使用。
譬如,使用 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%);
}
}
或者可以使用 postcss-use] 直接在 CSS 里启用插件:
@use autoprefixer(browsers: ['last 2 versions']);
:fullscreen a {
display: flex
}
打包
postcss-utilitiesincludes the most commonly used mixins, shortcuts and helpers to use as@utilrules.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.oldiecontains plugins that transform your CSS for older Internet Explorer compatibility.precsscontains plugins that allow you to use Sass-like CSS.rucksackcontains plugins to speed up CSS development with new features and shortcuts.level4contains only plugins that let you write CSS4 without the IE9 fallbacks.shortadds and extends numerous shorthand properties.stylelintcontains plugins that lint your stylesheets.postcss-hamsterfor vertical rhythm, typography, modular scale functions.
面向未来的 CSS 语法
postcss-applysupports custom properties sets references.postcss-attribute-case-insensitivesupports case insensitive attributes.postcss-color-functionsupports functions to transform colors.postcss-color-graysupports thegray()function.postcss-color-hex-alphasupports#rrggbbaaand#rgbanotation.postcss-color-hsl: transforms CSS Colors 4hsl()to more compatiblehsl()orhsla().postcss-color-hwbtransformshwb()to widely compatiblergb().postcss-color-rebeccapurplesupports therebeccapurplecolor.postcss-color-rgb: transforms CSS Colors 4rgb()to more compatiblergb()orrgba().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-normalizeto normalize font, especiallyfont-family.postcss-font-varianttranspiles human-readablefont-variantto more widely supported CSS.postcss-font-family-system-uitransforms W3C CSSfont-family: system-uito a practical font list.postcss-hostmakes the Shadow DOM’s:hostselector work properly with pseudo-classes.postcss-initialsupportsinitialkeyword andall: initialto clean inherit styles.postcss-logical-propertiestransformsstartandendproperties toleftandrightdepending on the writing direction of the document.postcss-bidirectiongenerate left-to-right and right-to-left styles with single syntax.postcss-media-minmaxadds<=and=>statements to media queries.postcss-pseudo-class-any-linkadds:any-linkpseudo-class.postcss-selector-nottransforms CSS4:not()to CSS3:not().postcss-selector-matchestransforms CSS4:matches()to more compatible CSS.postcss-start-to-endlets you control your layout (LTR or RTL) through logical rather than direction / physical rules.mq4-hover-shimsupports the@media (hover)feature.
See also cssnext plugins pack to add future CSS syntax by one line of code.
向下兼容
postcss-color-rgba-fallbacktransformsrgba()to hexadecimal.postcss-disabledadds a[disabled]attribute and/or a.disabledclass when the:disabledpseudo class is present.postcss-epubadds the-epub-prefix to relevant properties.postcss-esplitsplits your CSS exceeding 4095 selectors for IE.postcss-fallbackaddsfallbackfunction to avoid duplicate declarations.postcss-filter-gradientadds gradient filter for the old IE.postcss-flexibilityadds-js-prefix forFlexibility polyfill.postcss-gradient-transparency-fixtransformstransparentvalues in gradients to support Safari's different color interpolation.postcss-hash-classnameappend hash string to your css class name.postcss-mqwidth-to-classconverts min/max-width media queries to classes.postcss-opacityadds opacity filter for IE8.postcss-pseudoelementsConvert::selectors into:selectors for IE 8 compatibility.postcss-round-subpixelsplugin that rounds sub-pixel values to the nearest full pixel.postcss-unmqremoves media queries while preserving desktop rules for IE≤8.postcss-vmingeneratesvmfallback forvminunit in IE9.postcss-will-changeinserts 3D hack beforewill-changeproperty.autoprefixeradds vendor prefixes for you, using data from Can I Use.postcss-piemakes IE several of the most useful CSS3 decoration features.cssgraceprovides various helpers and transpiles CSS 3 for IE and other old browsers.pixremgenerates pixel fallbacks forremunits.postcss-fixieadds easy and painless IE hacks
See also oldie plugins pack.
语言扩展
postcss-aspect-ratiofix an element's dimensions to an aspect ratio.postcss-atrootplace rules directly at the root node.postcss-bemadds at-rules for BEM and SUIT style classes.postcss-clickallows to use the:clickpseudo class and implement it in JavaScript.postcss-compact-mqprovides compact syntax for media queries based on viewport width.postcss-conditionalsadds@ifstatements.postcss-css-variablessupports variables for selectors, and at-rules using W3C similar syntax.postcss-current-selectorto get current selector in declaration.postcss-define-propertyto define properties shortcut.postcss-define-functionto implement Sass@functiondirective.postcss-eachadds@eachstatement.postcss-foradds@forloops.postcss-at-rules-variablesadds support for custom properties in@for,@each,@if, etc.postcss-functionsenables exposure of JavaScript functions.postcss-if-mediainline or nest media queries within CSS rules & properties.postcss-local-constantsadds support for localized constants.postcss-mapenables configuration maps.postcss-matchadds@matchfor Rust-style pattern matching.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-namespaceprefix a namespace to a selector.postcss-nestedunwraps nested rules.postcss-nested-propsunwraps nested properties.postcss-nested-varssupports nested Sass-style variables.postcss-pseudo-class-any-buttonadds:any-buttonpseudo-class for targeting all button elements.postcss-pseudo-class-entertransforms:enterinto:hoverand:focus.postcss-quantity-queriesenables quantity queries.postcss-refrefers properties from another rule.postcss-reverse-mediareverse/Invert media query parameters.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.postcss-vertical-rhythm-functionadds a vertical rhythmvr()function that is unit agnostic and works in situations where the font-size cannot be calculated during build time.postcss-responsive-propertiesallows you to write responsive property values.postcss-text-remove-gapremove space before and after text strings, added by line-height and extra space in glyph itself.postcss-closestplugin to modify closest matching part of current selector.csstyleadds components workflow to your styles.postcss-percentagesupport Sass-likepercentage()function.postcss-state-selectorwrite CSS based on component's state.
See also precss plugins pack to add them by one line of code.
颜色
postcss-ase-colorsreplaces color names with values read from an ASE palette file.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-color-yiqsets foreground colors using the YIQ color space.postcss-colorblindtransforms colors using filters to simulate colorblindness.postcss-contrastchecks background-color and gives either white or black.postcss-hexrgbaadds shorthand hexrgba(hex, alpha)method.postcss-rgb-plzconverts 3 or 6 digit hex values torgb.postcss-rgba-hexconvertsrgbavalues tohexanalogues.postcss-shades-of-grayhelps keeping grayscale colors consistent to a gray palette.colorguardhelps maintain a consistent color palette.postcss-get-colorget the prominent colors from an image.postcss-randomcolorsupports function to use random color.
图片与字体
postcss-assetsallows you to simplify URLs, insert image dimensions, and inline files.postcss-assets-rebaserebases assets fromurl().postcss-at2xhandles retina background images via use ofat-2xkeyword.postcss-border-9-patchgenerates 9-patch like border styles via a custom rule.postcss-cachebusteradds version parameter to images and fontspostcss-copy-assetscopies assets referenced by relativeurl()s into a build directory.postcss-data-packermoves embedded Base64 data to a separate file.postcss-easyspritescombine images to sprites, based on their image.png#hashand aspect ratio (@2x).postcss-image-setaddsbackground-imagewith first image forimage-set().postcss-image-inlinerinlines local and remote images.postcss-instagramadds Instagram filters tofilter.postcss-filter-tintadds tint filter to elements such as images.postcss-font-awesomeadds an easy shortcut to font-awesome unicode codespostcss-font-packsimplifies font declarations and validates they match configured font packs.postcss-fontpathadds font links for different browsers.postcss-lazyimagecssadds image width and height automatically.postcss-lazyspritegenerates sprites from the directory of images.postcss-placeholdmakes it easy to drop in placeholder images.postcss-resemble-imageprovides a gradient fallback for an image that loosely resembles the original.postcss-responsive-imagesadds stylesheets for making your images responsive.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-unicode-charactersmakes it easier to writeunicode-rangedescriptors.postcss-urlrebases or inlinesurl()s.postcss-urlrevadds MD5 hash strings tourl()s.postcss-write-svgwrite inline SVGs in CSS.postcss-inline-svginline SVG images and customize their styles.webpcssadds URLs for WebP images for browsers that support WebP.
网格
postcss-gridadds a semantic grid system.postcss-grid-kisstransforms ASCII-art grids into CSS Grid layout.postcss-grid-systemcreates grids based on a fixed column width.postcss-grid-fluidcreates fluid grids.postcss-layouta plugin for some common CSS layout patterns and a Grid system.postcss-mazeis a mobile first, semantic responsive grid to suit any design pattern.postcss-neatis a semantic and fluid grid framework.postcss-oldschool-gridis a grid system with wrapping columns and padding gutters.postcss-simple-gridcreate grid with one line.lostfeature-richcalc()grid system by Jeet author.
优化
postcss-calcreducescalc()to values (when expressions involve the same units).postcss-combine-duplicated-selectorsautomatically join identical css selectors.postcss-filter-mqFilter all matching or non-matching media queries.postcss-importinlines the stylesheets referred to by@importrules.postcss-nested-importinlines stylesheets referred to by@importrules inside nested rule blocks.postcss-partial-importinlines standard imports and Sass-like partials.postcss-referenceemulates Less’s [@import (reference)].postcss-remove-rootremoves all instances of:rootfrom a stylesheet.postcss-single-charsetensures that there is one and only one@charsetrule at the top of file.postcss-zindexrebases positivez-indexvalues.postcss-unprefixUnprefixes vendor prefixes in legacy CSS.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.postcss-mq-optimizeremoves invalid media queries or its expresions.postcss-uncssremoves unused CSS from your stylesheets.postcss-html-filterfilters out CSS that does not apply to the HTML you provide.postcss-no-importantdelete declarations !important.
See also plugins in modular minifier cssnano.
快捷工具
postcss-aliascreates shorter aliases for properties.postcss-alias-atrulescreates shorter aliases for at-rules.postcss-all-link-colorsinsert colors for link-related pseudo-classes.postcss-borderadds shorthand for width and color of all borders inborderproperty.postcss-border-shortcutPostCSS plugin for assign defaultbordertype if not expressed.postcss-buttoncreates buttons.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-hiddenallows for easy ways to hide elements.postcss-input-styleadds new pseudo-elements for cross-browser styling of inputs.postcss-parent-selectoradds a parent selector to the beginning of all rules.postcss-positionadds shorthand declarations for position attributes.postcss-property-lookupallows referencing property values without a variable.postcss-responsive-typechangesfont-sizedepends on screen size.postcss-scribdefine your own aliases/shortcuts for properties or values.postcss-short-font-sizeextendsfont-sizeto define line-height s a second value.postcss-short-positionextendspositionto define edges as additional values.postcss-short-spacingextendsmarginandpaddingto allow or omitted edges.postcss-short-textadds atextshortcut property for several text-related properties.postcss-sizeadds asizeshortcut that sets width and height with one declaration.postcss-speech-bubbleadds speech bubbles of different kinds with just a couple of lines of CSS.postcss-transform-shortcutallows shorthand transform properties in CSS.postcss-trianglecreates a triangle.postcss-typescalesets type based on a typographic scale.postcss-verthorzadds vertical and horizontal spacing declarations.font-magiciangenerates all the@font-facerules needed in CSS.postcss-animationPostCSS plugin that adds@keyframesfrom animate.css.postcss-magic-animationsPostCSS plugin that adds@keyframesfrom Magic Animations.
其它
postcss-alter-property-valuealters your CSS declarations from a rule based configuration.postcss-attribute-selector-prefixadds a prefix to attribute selectorspostcss-autoresetautomatically adds reset styles.postcss-bomadds a UTF-8 BOM to files.postcss-camelcasertransforms selectors to CamelCase.postcss-class-prefixadds a prefix/namespace to class selectors.postcss-currencyreplaces name of currency with symbols.postcss-eolreplaces EOL of files.postcss-extract-valueextracts values from css properties and puts them into variables.postcss-fakeidtransforms#fooIDs to attribute selectors[id="foo"].postcss-filter-streamblacklist files / folders that you don't want to process with a PostCSS plugin.postcss-flexboxeasy way to understand and start using CSS3 Flexbox.postcss-flexboxfixerunprefixes-webkit-only flexbox in legacy CSS.postcss-flexbugs-fixesfixes some of known flexbox bugs.postcss-gradientfixerunprefixes-webkit-only gradients in legacy CSS.postcss-hashreplaces output file names with hash algorithms for cache busting.postcss-ie8strips out unsupported properties and media queries for IE8.postcss-increase-specificityincreases the specificity of your selectors.postcss-inline-rtlconverts your CSS to right-to-left, but inline (adding just what you need).postcss-letter-trackinggenerates relative, Photoshop-compatible letter tracking for improved letter spacing.postcss-light-textadds-webkit-antialiasing for light text.postcss-modulesallows to use CSS Modules everywhere.postcss-mq-keyframesmoves any animation keyframes in media queries to the end of the file.postcss-mq-lastgives media query rules precedence by moving them to the end of the file.postcss-node-modules-replacerreplaces path than includesnode_modulesto~.postcss-pseudo-content-insertaddscontent: ''to:beforeand:afterif it is missing.postcss-pseudo-element-casesconverts.style::BEFOREinto.style::beforeand vice versa.postcss-pseudo-element-colonsconverts.style:beforeinto.style::beforeand vice versa.postcss-pseudo-elements-contentaddscontent: ''to:before-cand:after-c.postcss-pxtoremconverts pixel units torem.postcss-rawprotects nodes inside@rawat-rules from being touched by other plugins.postcss-remove-prefixesremoves vendor prefixes.postcss-safe-importantadds!importantto style declarations safely.postcss-sanitizeremove properties and values using rules (css sanitization).postcss-scopifyadds a user input scope to each selector.postcss-selectselect rules based off a selector list.postcss-selector-prefixeradds a prefix to css selectors.postcss-shorthand-expandexpands shorthand properties.postcss-sortingsort rules content with specified order.postcss-style-guidegenerates a style guide automatically.css-declaration-sortersorts CSS declarations fast and automatically in a certain order.perfectionistformats poorly written CSS and renders a “pretty” result.rtlcssmirrors styles for right-to-left locales.stylefmtmodern CSS formatter that works well withstylelint.postcss-autocorrectCorrects typos and notifies in the console.
分析
postcss-bem-linterlints CSS for conformance to SUIT CSS methodology.postcss-cssstatsreturns an object with CSS statistics.postcss-regexp-detectsearch for regexp in CSS declarations.postcss-stylestatsreturns a data 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.
反馈报告
postcss-browser-reporterdisplays warning messages from other plugins right in your browser.postcss-forced-variablesprovides warnings and errors when specified properties don't use variables.postcss-reporterlogs warnings and other messages from other plugins in the console.
有趣的项目
postcss-australian-stylesheetsAustralian Style Sheets.postcss-andalusian-stylesheetsAndalusian Style Sheets.postcss-canadian-stylesheetsCanadian Style Sheets.postcss-chinese-stylesheetsChinese Style Sheets.postcss-czech-stylesheetsCzech Style Sheets.postcss-german-stylesheetsGerman Style Sheets.postcss-italian-stylesheetsItalian Style Sheets.postcss-russian-stylesheetsRussian Style Sheets.postcss-swedish-stylesheetsSwedish Style Sheets.postcss-tatar-stylesheetsTatar Style Sheetspostcss-trollingTrolling Style Sheets.postcss-lolcat-stylesheetsLolspeak 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.postcss-spanish-stylesheetsSpanish Style Sheets.postcss-nopelets you writenopeinstead ofnone.