• Stars
    star
    126
  • Rank 284,543 (Top 6 %)
  • Language
    JavaScript
  • License
    Creative Commons ...
  • Created over 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Use Sass-like variables, conditionals, and iterators in CSS

PostCSS Advanced Variables PostCSS Logo

NPM Version Build Status Test Status Support Chat

PostCSS Advanced Variables lets you use Sass-like variables, conditionals, and iterators in CSS.

$dir: assets/icons;

@each $icon in (foo, bar, baz) {
  .icon-$icon {
    background: url('$dir/$icon.png');
  }
}

@for $count from 1 to 5 by 2 {
  @if $count > 2 {
    .col-$count {
      width: #{$count}0%;
    }
  }
}

@import "path/to/some-file";

/* after */

.icon-foo {
  background: url('assets/icons/foo.png');
}

.icon-bar {
  background: url('assets/icons/bar.png');
}

.icon-baz {
  background: url('assets/icons/baz.png');
}

.col-3 {
  width: 30%;
}

.col-5 {
  width: 50%;
}

// the contents of "path/to/_some-file.scss"

Usage

Add PostCSS Advanced Variables to your build tool:

npm install postcss-advanced-variables --save-dev

Node

Use PostCSS Advanced Variables to process your CSS:

require('postcss-advanced-variables').process(YOUR_CSS);

PostCSS

Add PostCSS to your build tool:

npm install postcss --save-dev

Use PostCSS Advanced Variables as a plugin:

postcss([
  require('postcss-advanced-variables')(/* options */)
]).process(YOUR_CSS);

Gulp

Add Gulp PostCSS to your build tool:

npm install gulp-postcss --save-dev

Use PostCSS Advanced Variables in your Gulpfile:

var postcss = require('gulp-postcss');

gulp.task('css', function () {
  return gulp.src('./src/*.css').pipe(
    postcss([
      require('postcss-advanced-variables')(/* options */)
    ])
  ).pipe(
    gulp.dest('.')
  );
});

Grunt

Add Grunt PostCSS to your build tool:

npm install grunt-postcss --save-dev

Use PostCSS Advanced Variables in your Gruntfile:

grunt.loadNpmTasks('grunt-postcss');

grunt.initConfig({
  postcss: {
    options: {
      use: [
        require('postcss-advanced-variables')(/* options */)
      ]
    },
    dist: {
      src: '*.css'
    }
  }
});

Features

$variables

Variables let you store information to be reused anywhere in a stylesheet.

Variables are set just like CSS properties, placing a $ symbol before the name of the variable ($var-name). They may also be set placing a $ symbol before two parentheses wrapping the name of the variable ($(var-name)), or by wrapping the $ symbol and variable name in curly braces preceeded by a hash (#{$var-name}).

$font-size:     1.25em;
$font-stack:    "Helvetica Neue", sans-serif;
$primary-color: #333;

body {
  font: $font-size $(font-stack);
  color: #{$primary-color};
}

*Note: To use #{$var-name} without issues, you will need to include the PostCSS SCSS Syntax.

In that example, $font-size, $font-stack, and $primary-color are replaced with their values.

body {
  font: 1.25em "Helvetica Neue", sans-serif;
  color: #333;
}

@if and @else Rules

Conditionals like @if and @else let you use rules in a stylesheet if they evaluate true or false.

Conditionals are set by writing @if before the expression you want to evaluate. If the expression is true, then its contents are included in the stylesheet. If the expression is false, then its contents are not included, but the contents of an @else that follows it are included.

$type: monster;

p {
  @if $type == ocean {
    color: blue;
  } @else {
    color: black;
  }
}

In that example, $type === ocean is false, so the @if contents are ignored and the @else contents are used.

p {
  color: black;
}

@for and @each Rules

Iterators like @for and @each let you repeat content in a stylesheet.

A @for statement repeats by a numerical counter defined as a variable.

It can be written as @for $counter from <start> through <end> where $counter is the name of the iterating variable, <start> is the number to start with, and <end> is the number to finish with.

It can also be written as @for $counter from <start> to <end> where $counter is still the name of the counter variable, <start> is still the number to start with, but <end> is now the number to finish before, but not include.

When <start> is greater than <end>, the counter will decrement instead of increment.

Either form of @for can be written as @for $var from <start> to <end> by <increment> or @for $var from <start> through <end> by <increment> where <incremement> is the amount the counter variable will advance.

@for $i from 1 through 5 by 2 {
  .width-#{$i} {
    width: #{$i}0em;
  }
}

@for $j from 1 to 5 by 2 {
  .height-#{$j} {
    height: #{$j}0em;
  }
}

In that example, $i is repeated from 1 through 5 by 2, which means it is repeated 3 times (1, 3, and 5). Meanwhile, $j is repeated from 1 to 5 by 2, which means it is repeated 2 times (1 and 3).

.width-1 {
  width: 10em;
}

.width-3 {
  width: 30em;
}

.width-5 {
  width: 50em;
}

.height-1 {
  height: 10em;
}

.height-3 {
  height: 30em;
}

An @each statement statement repeats through a list of values.

It can be written as @each $item in $list where $item is the name of the iterating variable and $list is the list of values being looped over.

@each $animal in (puma, sea-slug, egret, salamander) {
  .#{$animal}-icon {
    background-image: url("images/icon-#{$animal}.svg");
  }
}

In that example, a list of 4 animals is looped over to create 4 unique classnames.

.puma-icon {
  background-image: url("images/icon-puma.svg");
}

.sea-slug-icon {
  background-image: url("images/icon-sea-slug.svg");
}

.egret-icon {
  background-image: url("images/icon-egret.svg");
}

.salamander-icon {
  background-image: url("images/icon-salamander.svg");
}

It can also be written as @each $item $counter in $list where $item is still the name of the iterating variable and $list is still the list of values being looped over, but now $counter is the numerical counter.

@each $animal $i in (puma, sea-slug, egret, salamander) {
  .#{$animal}-icon {
    background-image: url("images/icon-#{$i}.svg");
  }
}
.puma-icon {
  background-image: url("images/icon-1.svg");
}

.sea-slug-icon {
  background-image: url("images/icon-2.svg");
}

.egret-icon {
  background-image: url("images/icon-3.svg");
}

.salamander-icon {
  background-image: url("images/icon-4.svg");
}

In that example, a list of 4 animals is looped over to create 4 unique classnames.

@mixin, @include, and @content rules

Mixins let you reuse rule in a stylesheet. A @mixin defines the content you want to reuse, while an @include rule includes it anywhere in your stylesheet.

Mixins are set by writing @mixin before the name of the mixin you define. This can be (optionally) followed by comma-separated variables you want to use inside of it. Mixins are then used anywhere by writing @include before the name of the mixin you are using. This is (again, optionally) followed by some comma-separated arguments you want to pass into the mixin as the (aforementioned) variables.

@mixin heading-text {
  color: #242424;
  font-size: 4em;
}

h1, h2, h3 {
  @include heading-text;
}

.some-heading-component > :first-child {
  @include heading-text;
}

In that example, @include heading-text is replaced with its contents.

h1, h2, h3 {
  color: #242424;
  font-size: 4em;
}

.some-heading-component > :first-child {
  color: #242424;
  font-size: 4em;
}

Remember, mixins can be followed by comma-separated variables you want to pass into the mixin as variables.

@mixin heading-text($color: #242424, $font-size: 4em) {
  color: $color;
  font-size: $font-size;
}

h1, h2, h3 {
  @include heading-text;
}

.some-heading-component > :first-child {
  @include heading-text(#111111, 6em);
}

In that example, @include heading-text is replaced with its contents, but this time some of their contents are customized with variables.

h1, h2, h3 {
  color: #242424;
  font-size: 4em;
}

.some-heading-component > :first-child {
  color: #111111;
  font-size: 6em;
}

Options

variables

The variables option defines global variables used when they cannot be resolved automatically.

require('postcss-advanced-variables')({
  variables: {
    'site-width': '960px'
  }
});

The variables option also accepts a function, which is given 2 arguments; the name of the unresolved variable, and the PostCSS node that used it.

require('postcss-advanced-variables')({
  variables(name, node) {
    if (name === 'site-width') {
      return '960px';
    }

    return undefined;
  }
});
.hero {
  max-width: $site-width;
}

/* after */

.hero {
  max-width: 960px;
}

unresolved

The unresolved option defines how unresolved variables, mixins, and imports should be handled. The available options are throw, warn, and ignore. The default option is to throw.

require('postcss-advanced-variables')({
  unresolved: 'ignore' // ignore unresolved variables
});

disable

The disable option defines which features should be disabled in PostCSS Advanced Variables.

The disable option can be a string or an array, and the features that can be disabled are @content, @each, @else, @if, @include, @import, @for, and @mixin.

require('postcss-advanced-variables')({
  disable: '@mixin, @include, @content' // ignore @mixin, @include, and @content at-rules
});

Import Options

These options only apply to the @import at-rule.

importPaths

The importPaths option defines a path or multiple paths used to lookup files when they cannot be found automatically.

The importPaths option can be a string or an array.

By default, imports are resolved using the Sass Import Resolve Specification.

require('postcss-advanced-variables')({
  importPaths: ['path/to/files', 'another/path/to/files']
});

importResolve

The importResolve option defines the file resolver used by imports. It is a function given 3 arguments; the url id, the current working directory, and the options processed by PostCSS Advanced Variables.

The importResolve function should return a Promise with an object containing the full path (file) and the contents of the file (contents).

const resolve = require('custom-resolver');

require('postcss-advanced-variables')({
  // a resolver may work many ways, and this is just an example
  importResolve: (id, cwd, opts) => resolve({ id, cwd });
});

importFilter

The importFilter option determines whether an import will be inlined.

The value can be a function or an regular expression. When providing a function, it is called with a single string argument id and returns true when the import should be inlined. When providing a regular expression, if the id matches the expression, the import will be inlined.

By default, imports are ignored if they begin with a protocol or protocol-relative slashes (//).

require('postcss-advanced-variables')({
  importFilter: (id) => {
    return ['ignore', 'these', 'imports'].contains(id);
  }
});

importRoot

The importRoot option defines the root directory used by imports when the current directory cannot be detected. Its default value is process.cwd().

require('postcss-advanced-variables')({
  importRoot: 'path/to/root'
});

importCache

The importCache option defines a cache made available to the options object that may be used by the file resolver.

const sharedCache = {};

require('postcss-advanced-variables')({
  importCache: sharedCache
});

More Repositories

1

sanitize.css

A best-practices CSS foundation
CSS
5,192
star
2

postcss-preset-env

Convert modern CSS into something browsers understand
CSS
2,219
star
3

precss

Use Sass-like markup in your CSS
CSS
1,609
star
4

postcss-font-magician

Magically generate all the @font-face rules
JavaScript
1,002
star
5

postcss-plugins

PostCSS Tools and Plugins
CSS
871
star
6

postcss-normalize

Use the parts of normalize.css (or sanitize.css) you need from your browserslist
CSS
816
star
7

postcss-write-svg

Write SVGs directly in CSS
JavaScript
755
star
8

mdcss

Easily create and maintain style guides using CSS comments
JavaScript
686
star
9

cssdb

A database of staged CSS features
JavaScript
522
star
10

system-font-css

Use the native system font of the OS running the browser
HTML
521
star
11

normalize.css

A cross-browser CSS foundation
HTML
473
star
12

postcss-nesting

Nest style rules inside each other
CSS
451
star
13

postcss-custom-media

Use Custom Media Queries in CSS, following the CSS Media Queries specification
JavaScript
438
star
14

postcss-short

Use advanced shorthand properties in CSS
JavaScript
189
star
15

oldie

Compile CSS compatible with old Internet Explorer
JavaScript
168
star
16

postcss-time-machine

Fix mistakes in the design of CSS itself
JavaScript
159
star
17

postcss-logical

Use logical properties and flow-relative values in CSS
JavaScript
137
star
18

postcss-sass

Use Sass as a PostCSS plugin
JavaScript
136
star
19

postcss-custom-selectors

Use Custom Selectors in CSS
JavaScript
131
star
20

react-app-rewire-postcss

Configure PostCSS in Create React App without ejecting
JavaScript
114
star
21

css-typed-om

Use CSS Typed Object Model in the browser
JavaScript
101
star
22

css-prefers-color-scheme

Use light or dark color themes in CSS
JavaScript
99
star
23

postcss-color-mod-function

Modify colors using the color-mod() function in CSS
JavaScript
96
star
24

postcss-language

Support for modern and experimental CSS within Visual Studio Code
77
star
25

postcss-partial-import

Inline sugary @import statements in CSS
JavaScript
72
star
26

tokenizer

Tokenize CSS according to the CSS Syntax
TypeScript
67
star
27

parser

CSS Parser
JavaScript
63
star
28

stylelint-value-no-unknown-custom-properties

A stylelint rule to catch usage of unknown custom properties
JavaScript
63
star
29

postcss-conic-gradient

Use conic gradients in your CSS files
JavaScript
60
star
30

postcss-wcag-contrast

Check CSS for WCAG color contrast compliance
JavaScript
59
star
31

postcss-env-function

Use env() variables in CSS
JavaScript
54
star
32

postcss-focus-visible

Use the :focus-visible pseudo-selector in CSS
CSS
53
star
33

postcss-extend-rule

Use the @extend at-rule and functional selectors in CSS
JavaScript
51
star
34

stylelint-use-logical

Enforce usage of logical properties and values in CSS
JavaScript
50
star
35

postcss-selector-not

PostCSS plugin to transform :not() W3C CSS level 4 pseudo class to more compatible CSS (multiple css3 :not() selectors)
JavaScript
48
star
36

postcss-transform-shortcut

Use shorthand transform properties in CSS
JavaScript
48
star
37

postcss-lab-function

Use lab() and lch() color functions in CSS
JavaScript
48
star
38

postcss-input-range

Use unprefixed input range selectors in CSS
JavaScript
42
star
39

stylelint-use-nesting

Enforce nesting when it is possible in CSS
JavaScript
40
star
40

postcss-unmq

Remove media queries from CSS while preserving rules that match a hard-coded viewport
JavaScript
37
star
41

css-has-pseudo

Style elements relative to other elements
JavaScript
35
star
42

postcss-image-set-function

Use image-set() in CSS
CSS
34
star
43

postcss-focus-within

Use the :focus-within pseudo-selector in CSS
CSS
30
star
44

postcss-pseudo-class-enter

Use the :enter pseudo-class in CSS
JavaScript
28
star
45

postcss-is-pseudo-class

Match elements by inner selectors in CSS
JavaScript
27
star
46

postcss-pseudo-class-any-link

Use the :any-link pseudo-class in CSS
JavaScript
24
star
47

postcss-short-size

Use size properties in CSS
JavaScript
21
star
48

postcss-gap-properties

Use the gap, column-gap, and row-gap shorthand properties in CSS
JavaScript
20
star
49

custom-units

Use Custom Units in CSS
JavaScript
18
star
50

postcss-dir-pseudo-class

Use the :dir() pseudo-class to style by directionality in CSS
JavaScript
16
star
51

postcss-media-fn

Use media() to assign responsive values to a property
JavaScript
15
star
52

postcss-font-weights

Use common font weights in CSS
CSS
15
star
53

create-postcss-plugin

Quickly create new PostCSS plugins
JavaScript
15
star
54

postcss-tape

Quickly test PostCSS plugins
JavaScript
15
star
55

super-postcss

Now youโ€™re playing with PostCSS โ€” Super PostCSS!
JavaScript
14
star
56

postcss-register-property

Register properties in CSS
JavaScript
14
star
57

postcss-inset

Use the inset property in CSS
JavaScript
13
star
58

postcss-trig

Use trigonometry functions in CSS
JavaScript
12
star
59

postcss-export-custom-variables

Export custom media queries, custom properties, custom property sets, and custom selectors from CSS to JS
JavaScript
12
star
60

stylelint-media-use-custom-media

Enforce usage of custom media queries in CSS
JavaScript
11
star
61

postcss-at-else

Use at-else inverted media queries in CSS
CSS
11
star
62

postcss-list-style-safari-fix

Remove list styles in CSS without preventing VoiceOver from announcing them in Safari
JavaScript
11
star
63

postcss-resolve-nested-selector

Resolve a nested selector in a PostCSS AST
JavaScript
10
star
64

postcss-place

place-* shorthand for align-* and justify-*
JavaScript
10
star
65

css-blank-pseudo

Style form elements when they are empty
JavaScript
10
star
66

postcss-short-spacing

Omit sides within margin and padding properties in CSS
JavaScript
10
star
67

js-custom-media

Use Custom Media Queries in JS
JavaScript
9
star
68

postcss-browser-comments

Keep only the CSS you need based on comments and your browserslist
CSS
9
star
69

babel-plugin-import-postcss

Import processed CSS files in JS
JavaScript
8
star
70

postcss-to-nest

Transform unnested CSS into nested CSS
JavaScript
8
star
71

css-import-resolve

An algorithm for resolving imports in CSS
JavaScript
8
star
72

postcss-color-functional-notation

Use space and slash separated color notation in CSS
JavaScript
8
star
73

postcss-attribute-case-insensitive

PostCSS plugin to support case insensitive attributes
JavaScript
8
star
74

postcss-custom-utils

Read, write, and transform Custom Media and Custom Properties from almost anywhere
JavaScript
7
star
75

postcss-preset-env-www

The official website for PostCSS Preset Env
HTML
7
star
76

postcss-short-data

Use shorthand data attribute selectors in CSS
JavaScript
7
star
77

postcss-sass-extend

Use @extend and placeholder classes as you would in Sass
JavaScript
6
star
78

postcss-module-import

Inline import statements as CSS Modules
JavaScript
6
star
79

postcss-visitor

Transform CSS with visitor-based plugins
JavaScript
6
star
80

postcss-infrared-filter

Use an infrared photography filter in CSS
JavaScript
6
star
81

postcss-short-position

Define sides within the position property in CSS
JavaScript
6
star
82

postcss-commas

Declare multiple, comma-separated properties
JavaScript
6
star
83

postcss-short-border

Define multiple sides on border properties in CSS
CSS
6
star
84

postcss-double-position-gradients

Use double-position gradients in CSS
JavaScript
6
star
85

stylelint-devtool-prop-order

Enforce CSS property ordering like Chrome DevTools
JavaScript
5
star
86

cccp

Compact Client-side Compatible PostCSS
JavaScript
5
star
87

postcss-short-color

Define background-color within the color property in CSS
JavaScript
5
star
88

postcss-bob-ross-palette

Bring Bob Ross to your CSS :)
JavaScript
5
star
89

postcss-overflow-shorthand

Use the overflow shorthand in CSS
JavaScript
5
star
90

postcss-vmax

Use vmax in Internet Explorer and Edge
JavaScript
5
star
91

postcss-number-functions

Use Sass Number Functions in CSS
JavaScript
5
star
92

postcss-short-font-size

Define line-height within the font-size property in CSS
CSS
4
star
93

create-stylelint-plugin

Quickly create new stylelint plugins
JavaScript
4
star
94

stylelint-color-control

Control color usage in CSS
JavaScript
4
star
95

postcss-unrgba

Convert rgba() values to hex
JavaScript
4
star
96

postcss-short-text

Use a shorthand text property in CSS
JavaScript
4
star
97

postcss-plugins-directory

JavaScript
4
star
98

parse

A tool to read CSS and do things with it in JavaScript
JavaScript
4
star
99

postcss-words

Transform CSS keywords into custom values in CSS
JavaScript
3
star
100

postcss-identifiers

Use identifiers in CSS to write intelligent shorthands
JavaScript
3
star