Giter VIP home page Giter VIP logo

postcss-mixins's Introduction

PostCSS Mixins

PostCSS plugin for mixins.

Note, that you must set this plugin before postcss-simple-vars and postcss-nested.

@define-mixin icon $network, $color: blue {
    .icon.is-$(network) {
        color: $color;
        @mixin-content;
    }
    .icon.is-$(network):hover {
        color: white;
        background: $color;
    }
}

@mixin icon twitter {
    background: url(twt.png);
}
@mixin icon youtube, red {
    background: url(youtube.png);
}
.icon.is-twitter {
    color: blue;
    background: url(twt.png);
}
.icon.is-twitter:hover {
    color: white;
    background: blue;
}
.icon.is-youtube {
    color: red;
    background: url(youtube.png);
}
.icon.is-youtube:hover {
    color: white;
    background: red;
}

postcss-utilities collection is better for clearfix and other popular hacks. For simple cases you can use postcss-define-property.

Sponsored by Evil Martians

Usage

Step 1: Install plugin:

npm install --save-dev postcss postcss-mixins

Step 2: Check your project for existed PostCSS config: postcss.config.js in the project root, "postcss" section in package.json or postcss in bundle config.

If you do not use PostCSS, add it according to [official docs] and set this plugin in settings.

Step 3: Add the plugin to plugins list:

module.exports = {
  plugins: [
+   require('postcss-mixins'),
    require('autoprefixer')
  ]
}

CSS Mixin

Simple template defined directly in CSS to prevent repeating yourself.

See postcss-simple-vars docs for arguments syntax.

You can use it with postcss-nested plugin:

@define-mixin icon $name {
    padding-left: 16px;
    &::after {
        content: "";
        background: url(/icons/$(name).png);
    }
}

.search {
    @mixin icon search;
}

Unlike Sass, PostCSS has no if or while statements. If you need some complicated logic, you should use function mixin.

Function Mixin

This type of mixin gives you full power of JavaScript. You can define this mixins in mixins option.

This type is ideal for CSS hacks or business logic.

Also you should use function mixin if you need to change property names in mixin, because postcss-simple-vars doesn’t support variables in properties yet.

First argument will be @mixin node, that called this mixin. You can insert your declarations or rule before or after this node. Other arguments will be taken from at-rule parameters.

See [PostCSS API] about nodes API.

require('postcss-mixins')({
    mixins: {
        icons: function (mixin, dir) {
            fs.readdirSync('/images/' + dir).forEach(function (file) {
                var icon = file.replace(/\.svg$/, '');
                var rule = postcss.rule({ selector: '.icon.icon-' + icon });
                rule.append({
                    prop:  'background',
                    value: 'url(' + dir + '/' + file + ')'
                });
                mixin.replaceWith(rule);
            });
        }
    }
});
@mixin icons signin;
.icon.icon-back { background: url(signin/back.svg) }
.icon.icon-secret { background: url(signin/secret.svg) }

You can also return an object if you don’t want to create each node manually:

require('postcss-mixins')({
    mixins: {
        image: function (mixin, path, dpi) {
            return {
                '&': {
                    background: 'url(' + path + ')'
                },
                ['@media (min-resolution: '+ dpi +'dpi)']: {
                    '&': {
                        background: 'url(' + path + '@2x)'
                    }
                }
            }
        }
    }
});

Mixin body will be in mixin.nodes:

var postcss = require('postcss');

require('postcss-mixins')({
    mixins: {
        hover: function (mixin) {
            let rule = postcss.rule({ selector: '&:hover, &.hover' });
            rule.append(mixin.nodes);
            mixin.replaceWith(rule);
        }
    }
});

Or you can use object instead of function:

require('postcss-mixins')({
    mixins: {
        clearfix: {
            '&::after': {
                content: '""',
                display: 'table',
                clear: 'both'
            }
        }
    }
});

Mixin Content

@mixin-content at-rule will be replaced with mixin @mixin children. For example, CSS mixins:

@define-mixin isIE {
    .isIE & {
        @mixin-content;
    }
}

or JS mixins:

require('postcss-mixins')({
    mixins: {
        isIe: function () {
            '@mixin-content': {},
        }
    }
});

could be used like this:

.foo {
    color: blue;

    @mixin isIE {
        color: red;
    }
}

// output
.foo { color: blue; }
.isIE .foo { color: red; }

Mixin parameters with comma

In order to pass a comma-separated value as an argument to a mixin, you can use the special single-arg keyword. For example:

@define-mixin transition $properties, $duration {
  transition-property: $properties;
  transition-duration: $duration;
}

.foo {
  @mixin transition single-arg(color, background-color), 0.5s;
}

Migration from Sass

If you need to use Sass and PostCSS mixins together (for example, while migration), you could use @add-mixin, instead of @mixin. Just put PostCSS after Sass.

// Legacy SCSS
@mixin old {
    …
}
@include old;

// New code
@define-mixin new {
    …
}
@add-mixin new;

Options

Call plugin function to set options:

postcss([ require('postcss-mixins')({ mixins: {} }) ])

mixins

Type: Object

Object of function mixins.

mixinsDir

Type: string|string[]

Autoload all mixins from one or more dirs. Mixin name will be taken from file name.

// gulpfile.js

require('postcss-mixins')({
    mixinsDir: path.join(__dirname, 'mixins')
})

// mixins/clearfix.js

module.exports = {
    '&::after': {
        content: '""',
        display: 'table',
        clear: 'both'
    }
}

// mixins/size.pcss

@define-mixin size $size {
    width: $size;
    height: $size;
}

// mixins/circle.sss

@define-mixin circle $size
  border-radius: 50%
  width: $size
  height: $size

mixinsFiles

Type: string|string[]

Similar to mixinsDir; except, you can provide fast-glob syntax to target or not target specific files.

require('postcss-mixins')({
    mixinsFiles: path.join(__dirname, 'mixins', '!(*.spec.js)')
})

silent

Remove unknown mixins and do not throw a error. Default is false.

postcss-mixins's People

Contributors

9renpoto avatar a-kon avatar ai avatar alexufo avatar ambar avatar andgra avatar benfrain avatar charlessuh avatar denisborovikov avatar dependabot[bot] avatar eddort avatar emkay avatar fshowalter avatar gillchristian avatar goldensunliu avatar hudochenkov avatar jednano avatar jgxumak avatar kermage avatar lamtranweb avatar madlittlemods avatar mesqalito avatar no23reason avatar pciarach avatar pridyok avatar sandrina-p avatar signalwerk avatar spacedawwwg avatar trysound avatar vast avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postcss-mixins's Issues

Cannot read property 'length' of undefined

I ran into a problem when trying to implement your functional 'icons' example, just as a proof of concept.

I have copied everything like for like (aside from postcss is declared as postcsscore in my gulpfile)...mixin name, folder/image setup but I am give the error as per the issue title...

var rule = postcsscore.rule('.icon.icon-' + icon); <-- this causes 'cannot read length of undefined'

Where as var rule = postcsscore.rule({selector: '.icon.icon-' + icon}); does not produce an error, however in the output it only outputs the first item, which in your example is: .icon.icon-back, the second icon does not output.

Any suggestions?

SugarSS syntax support for global mixins

Right now plugin does not support .sss files for mixins
What i do:

require('postcss-mixins')({
        mixinsDir: path.join(__dirname, 'mixins')
    }),

In that dir i have size.sss file:

@define-mixin size $size
    width: $size
    height: $size

What happens: mixin does not work, throws error on processing.
Expected that to work.

Option to normalize args

It would be nice if there were an option to normalize args, e.g. 'true'/'false' strings to booleans, and numbers to numbers instead of strings.

Importing mixins?

Did I understand correctly that mixins works only in the file where they are defined?

I'm using postcss with webpack. Have two css files. One contains mixin definition, in second one it's used. On build got this:

Undefined mixin myMixin
.test {
  @mixin myMixin;
  ^
}

ERROR in ./src/layouts/contact/styles.css
Module build failed: TypeError: Cannot call method 'toString' of undefined
    at new Input (/Users/jeron_diovis/dev/projects/MediaSapiens/react-boilerplate/node_modules/css-loader/node_modules/postcss/lib/input.js:29:24)
    at Object.parse [as default] (/Users/jeron_diovis/dev/projects/MediaSapiens/react-boilerplate/node_modules/css-loader/node_modules/postcss/lib/parse.js:17:17)
    at new LazyResult (/Users/jeron_diovis/dev/projects/MediaSapiens/react-boilerplate/node_modules/css-loader/node_modules/postcss/lib/lazy-result.js:54:42)
    at Processor.process (/Users/jeron_diovis/dev/projects/MediaSapiens/react-boilerplate/node_modules/css-loader/node_modules/postcss/lib/processor.js:30:16)
    at processCss (/Users/jeron_diovis/dev/projects/MediaSapiens/react-boilerplate/node_modules/css-loader/lib/processCss.js:170:24)
    at Object.module.exports (/Users/jeron_diovis/dev/projects/MediaSapiens/react-boilerplate/node_modules/css-loader/lib/loader.js:21:15)
 @ ./src/layouts/contact/component.js 27:17-40

To make mixin visible globally I must define it in JS, in mixins option?

Empty string always passed as first argument to mixin

const myMixin = (rule, x, y) => {
  console.log(x, y)
  return {}
}
.example {
  @mixin myMixin; /* => '' undefined */
  @mixin myMixin 50px; /* => '50px' undefined */
}

I would expect the first invocation to log undefined undefined, but instead it receives an empty string as the first argument. I assume this is a bug, since the second invocation logs 50px undefined instead of 50px ''.

I don't think passing an empty string is good, because I might want to check whether the mixin received an argument or not.

Defining default values for mixins defined in JS file

Sorry; this is likely due to my lack of understanding. I have a mixin defined in a JS file — it takes a couple of arguments so I am attempting to define it like this:

MakeSpinner: function ($backgroundColor, $highlightColor)  {
        return {
            "content": "''",
            "border": "'2px solid ' + $backgroundColor",
            "border-left-color": $highlightColor,
            "border-radius": "999px",
            "opacity": "0"
        };
    }

However, I get the error Undefined variable $backgroundColorwhich makes some sense as this is an argument rather than an actual variable.

How should I be writing this?

Allow to use = to define a mixin and + to use it

Like it works in Sass. It's a cool shorthand and I like to use it with tabbed syntax to write less & do more 💪

So instead of

@define-mixin icon $network $color {
    .icon.is-$(network) {
        color: $color;
    }
    .icon.is-$(network):hover {
        color: white;
        background: $color;
    }
}

@mixin icon twitter blue;
@mixin icon youtube red;

I suggest to allow next:

=icon $network $color {
    .icon.is-$(network) {
        color: $color;
    }
    .icon.is-$(network):hover {
        color: white;
        background: $color;
    }
}

+icon twitter blue;
+icon youtube red;

Complex mixins with an object as argument

Love the plugin, but I'm more or less struggling a little to write more complex mixins.

Can you somehow create a mixin that accepts an object as argument:

function(mixin, selector, {background, color}) {
}

// or in non es6:
function(mixin, selector, args) {
}

In the css I would imagine it looks something like this:

a {
  @mixin foo '&:hover', { background: 'yellow', color: 'red' };
}

I've tried searching the docs and tests but didn't find much, my knowledge of post css internals is somewhat also limited so digging inside the code did not help me find the answer (yet).

What about defining default params?

i'm trying to port some scss to postcss and cant find solution for this use case

@mixin grid-overlay($color: black, $px-offset: false) {
  body {
    background: linear-gradient(to top, rgba($color, .1) 5%, white 5%);
    background-size: 100% ($line-height-ratio) + em;
    @if($px-offset) {
      background-position: 0 $px-offset + px;
    }
  }
}

Passing value to named param in a mixin with multiple params

I'm having trouble figuring out how to pass a value to a specific param in to a mixin that has multiple params defined. For example, I have an unstyled list mixin:

@define-mixin unstyled-list( $margin: 0, $padding: 0, $itemMargin: 0, $itemPadding: 0 ) {
  @mixin clearfix;
  list-style-type: none;
  margin: $margin;
  padding: $padding;
  @mixin-content;

  & > li {
    margin: $itemMargin;
    padding: $itemPadding;
  }
}

How would I apply this mixin providing a value for just the $padding param, and taking the defaults for the others? Having trouble figuring out the correct syntax for this. Any help would be greatly appreciated.

Default if value is empty

When nesting mixins, passing along variable that is not defined, should also be undefined and default in the nested mixin.

Currently it seems to fill it with a blank value which makes it not use the default fallback value.

Demo

@define-mixin style-links $color: #f00 {
    foo: $color;
}

@define-mixin format-content $color {
    @mixin style-links $color;
}

.foo {
    @mixin format-content;
}

.bar {
    @mixin format-content #0ff;
}

I would expect:

.foo {
    foo: #f00;
}

.bar {
    foo: #0ff;
}

But currently the output is:

.foo {
    foo: ;
}

.bar {
    foo: #0ff;
}

Unable to Parse Variable in Color Function

For some reason, as of a recent update I'm unable to put a variable inside the color function. This used to work:

`.text {
    color: color(var(--mainColor) lightness(+10%));
}`

No it's throwing up this error:

Warning: Running "cssnext:dist" (cssnext) task
Warning: :22:26: Unable to parse color from string "var(--mainColor)" Use --force to continue.

Any idea why this is causing this error? Any help is appreciated. Thanks in advance!

Possible to allow nested syntax in mixin definitions (withou separate install of postcss-nested)?

A mixin definition is the only place that I want to allow nested syntax --- and that is because the limitations of at-rule mixin definitions mean I need to use nesting if I want to target pseudo-elements and pseudo-classes. Right now, to use nested syntax I need to run postcss-mixins and then run postcss-nested. This means that people on my team could actually use nested syntax wherever they want. Do you think it would be possible for the mixins plugin to parse nested syntax internally so that I could nest within definitions and otherwise not run my css through the postcss-nested plugin?

Option to turn off arg space separation

I understand this is going away in the next version, but it is throwing an error for the first argument for padding where it should take 1-4 space separated values in one argument. It would be nice to silence or turn that off until the next version comes out.

property name

Does argument work for property name?

@define-mixin item $prop {
    &-12 {
        $prop: 100%;
    }
    &-11 {
        $prop: 91.66666667%;
    }
    &-10 {
        $prop: 83.33333333%;
    }
    &-9 {
        $prop: 75%;
    }
    &-8 {
        $prop: 66.66666667%;
    }
    &-7 {
        $prop: 58.33333333%;
    }
    &-6 {
        $prop: 50%;
    }
    &-5 {
        $prop: 41.66666667%;
    }
    &-4 {
        $prop: 33.33333333%;
    }
    &-3 {
        $prop: 25%;
    }
    &-2 {
        $prop: 16.66666667%;
    }
    &-1 {
        $prop: 8.33333333%;
    }
}

[email protected] doesn't work?

I have the following mixin:

@define-mixin icon $top, $left, $width, $number {
  .icon-$(number) {
    background: url(../../images/icons1.png) no-repeat $top $left;
    width: $width;
    height: 35px;
    display: inline-block;
    text-align: center;
    margin-bottom: 1em
  }
}

@mixin icon -46px, -14px, 28px, 1
@mixin icon -96px, -14px, 28px, 2
@mixin icon -145px, -14px, 35px, 3
@mixin icon -46px, -14px, 28px, 4

This code does not generate four class definitions. The only thing that is generated is:

.icon-1
@mixin icon -96px {
  background: url(...) no-repeat -46px -14px;
  width: 28px;
  height: 35px;
  display: inline-block;
  text-align: center;
  margin-bottom: 1em
}

Unfortunately, it is no valid css.

Maybe, I am doing something wrong, but according to Readme, I think that it shoud generate four classes. It is my webpack setup:

postcss: [
    postcssImport({
      addDependencyTo: webpack
    }),
    postcssMixins(),
    postcssCSSNext({
      browsers: ['last 10 versions']
    })
  ],

Is postcssMixins() placed correctly?

Can't use CSS variable

I can't put a CSS variable in my mixin parameter. Here an exemple:
@mixin ui-element-size var(--ui-default-height) var(--r-gutter-x) 0.875rem;
will generate that:
line-height: var(--ui-default-height);

Media queries in mixins or mixins in media queries

I am using v4.0.1 and am having nested at-rule issues. I see that others have posted similar issues that were resolved by upgrading to v4.0.1, however this has not fixed my issue.

I have tried adding media queries to my mixin:
@define-mixin myMixin{
foo: bar;
@media (min-width: 480px ){
foo: bar;
}
}
and also tried adding my mixin inside my media query:
.myClass{
@mixin myMixin;
@media (min-width: 480px ){
@mixin myMixin;
}
}

In both cases, I am getting the following error:

Defining at-rules cannot contain statements

And the CSS in the media query is ignored (but it compiles).

Here is a list of my dependencies:
"dependencies": {
"autoprefixer": "^6.3.1",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"bower": "^1.7.2",
"gulp": "^3.9.0",
"gulp-autoprefixer": "^3.1.0",
"gulp-cssnano": "^2.0.0",
"gulp-imagemin": "^2.4.0",
"gulp-postcss": "^6.0.1",
"imagemin-pngquant": "^4.2.0",
"laravel-elixir": "^5.0.0",
"pixrem": "^3.0.0",
"postcss-conditionals": "^2.0.0",
"postcss-each": "^0.9.1",
"postcss-import": "^7.1.3",
"postcss-math": "0.0.1",
"postcss-mixins": "^4.0.1",
"postcss-nested": "^1.0.0",
"postcss-reporter": "^1.3.0",
"postcss-scss": "^0.1.3",
"postcss-simple-extend": "^1.0.0",
"postcss-simple-vars": "^1.1.0",
"precss": "^1.3.0",
"yargs": "^4.4.0"
}

Any thoughts? Thank you.

Define at-rules inside at-rules?

When I define at-rules inside at-rules, I get an error saying Defining at-rules cannot contain statements

The code that throws an error is something like below.

@define-mixin headings $from: 1, $to: 6 {
  @if $from >= 1 and $to <= 6 {
    @for $i from $from to $to {
      h$i {
        @extend base-heading;
      }
    }
  }
  @define-placeholder base-heading {
    @mixin-content;
  }
}

Any support or plan for solving this?

Undefined mixin on first run

With mixins I'm importing from node_modules

@import 'stylep-dropdown';

.c-dropcard--right {
  @mixin dropdown-callout-inline;
  @mixin dropdown-inline .5em 1em, 0, 289px;
  @mixin dropdown-solid var(--callout-bg-color), var(--grey-100), rgba(0, 0, 0, .75), 4px, var(--grey-600) 0 0 7px;
  @mixin dropdown-callout-solid var(--callout-bg-color), 0 0 3px 1px rgba(0, 0, 0, .4);
  @mixin dropdown-callout-left-top;
}

I'm getting an error:

[09:40:35] Starting 'css'...

events.js:154
      throw er; // Unhandled 'error' event
      ^
Error: postcss-mixins: /Users/Stephen/project/src/patterns/dropcard.css:17:3: Undefined mixin dropdown-callout-inline
.c-dropcard--right {
  @mixin dropdown-callout-inline;
  ^
  @mixin dropdown-inline .5em 1em, 0, 289px;

And with the same code on second run

[09:45:08] Starting 'css'...
[09:45:11] Finished 'css' after 2.88 s

It's seeming like there is a open loop where it can't read or refresh what's in node_modules on first run.

How to use mixin inside mixin?

Need help!
I'm trying to translate my scss recursion mixin, you can see my scss pen here .

I'm using PreCSS and here is my Postcss code:

$treeLevels: 20;
$treeIndentation: 6px;

@define-mixin treeItem $i{
    li{
        @if $i != 0{
            > .angular-ui-tree-handle{ padding-left: calc($treeIndentation * ($treeLevels - $i + 2));}
            @mixin treeItem calc($i - 1);
        }
    }
}
ul{ @mixin treeItem $treeLevels; }

and my result is:

ul li > .angular-ui-tree-handle { padding-left:12px;}
ul li li { @mixin treeItem calc(calc($treeLevels - 1) - 1);}
ul li li > .angular-ui-tree-handle { padding-left:18px;}

Support comments in function mixins

Would you merge a PR that added support for comments in function mixins, similar to these lines?

Unfortunately, I can't think of a better way than this:

export default function() {
  return {
    '// postcss-font-pack: ignore-next': {},
    font: '0/0 serif'
  };
}

Open to better suggestions.

Color definitions break params

When I only use one param, I can get hsl() color definitions to work, but when I use two, it breaks. It looks like it might parse the commas within the vars as separators. It also doesn't work when I specify the default value of $blend: var(--white).

:root {
  --white: hsl(0, 0%, 100%);
  --gray: hsl(0, 0%, 50%);
}

@define-mixin linkColorBlend $color, $blend {
  color: $color;

  &:hover {
    color: color($color blend($blend 50%));
  }
}

.link {
  @mixin linkColorBlend var(--gray), white;
}

I get this error message:

Module build failed: Error: /Users/msc/Sites/msc.com/modules/www/Styles/Mixins/LinkMixins.css:18:5: Unable to parse color from string "hsl(0,"
    at /Users/msc/Sites/msc.com/modules/www/Styles/Mixins/LinkMixins.css:18:5
    at Object.Color (/Users/msc/Sites/msc.com/node_modules/color/index.js:33:10)
    at Object.exports.blend (/Users/msc/Sites/msc.com/node_modules/css-color-function/lib/adjusters.js:39:15)
    at /Users/msc/Sites/msc.com/node_modules/css-color-function/lib/convert.js:56:20
    at Array.forEach (native)
    at toRGB (/Users/msc/Sites/msc.com/node_modules/css-color-function/lib/convert.js:42:7)
    at Object.convert (/Users/msc/Sites/msc.com/node_modules/css-color-function/lib/convert.js:28:10)
    at transformColor (/Users/msc/Sites/msc.com/node_modules/postcss-color-function/index.js:49:43)
    at transformColorValue (/Users/msc/Sites/msc.com/node_modules/postcss-color-function/index.js:20:16)
    at Object.tryCatch [as try] (/Users/msc/Sites/msc.com/node_modules/postcss-message-helpers/index.js:53:12)
    at transformDecl (/Users/msc/Sites/msc.com/node_modules/postcss-color-function/index.js:19:31)
 @ ./modules/www/ArchiveLink/ArchiveLink.css 4:14-216 13:2-17:4 14:20-222

influenced other attribute

like this:

first mixin:

@define-mixin height-line-height $height, $line-height {
  height: $height;
  line-height: $line-height;
  [data-dpr="2"] & {
    height: calc($height * 2);
    line-height: calc($line-height * 2);
  }
  [data-dpr="3"] & {
    height: calc($height * 3);
    line-height: calc($line-height * 3);
  }
}

second mixin:

@define-mixin font-dpr $font-size {
  font-size: $font-size;
  [data-dpr="2"] & {
    font-size: calc($font-size * 2);
  }
  [data-dpr="3"] & {
    font-size: calc($font-size * 3);
  }
}

my code:

image
and chrome show:
image
vertical-align is not working, i change this order, like this:

     vertical-align: top;
     display: inline-block;
     @mixin font-dpr 48px;
     /*@mixin height-line-height 48px, 48px;*/
    vertical-align: top;
    display: inline-block;
    font-size: 48px;

its ok;
when i use two mixins ;

case 1:

    vertical-align: top;
    display: inline-block;
    @mixin font-dpr 48px;
    @mixin height-line-height 48px, 48px;

got

    vertical-align: top;
    display: inline-block;
    font-size: 48px;
    line-height: 48px;

case 2:

     display: inline-block;
     @mixin font-dpr 48px;
     @mixin height-line-height 48px, 48px;
     vertical-align: top;

got

    display: inline-block;
    font-size: 48px;
    line-height: 48px;

case 3

    display: inline-block;
    @mixin font-dpr 48px;
    vertical-align: top;
    @mixin height-line-height 48px, 48px;
    display: inline-block;
    font-size: 48px;
    height: 48px;
    line-height: 48px;

i very like this mixin tools , i know you will help me :)

Conditionals inside a mixin

I'm trying to write a simple mixin like this one

module.exports = {
    button: function(size) {
        var ciccio = '177px';

        if (size == 'small') {
            ciccio = '99px';
        } else if (size == 'medium') {
            ciccio = '166px'
        } else if (size == 'big') {
            ciccio = '222px'
        }

        return {
            'background-color': 'red',
            'border': '2px solid black',
            'padding': '5px 10px',
            'width': ciccio
        }
    }
}

but when I compile postcss through webpack it throws this error...
'CssSyntaxError: Unknown word
if (size == 'small') {
return '99px';
^
} else if (size == 'medium') {...

What am I doing wrong? It's not possible to use if statements inside a mixin?

Replicating @mixin-content in a function mixin

I've been trying to replicate the functionality of my css mixin as a function mixin but I can't figure out how to the equivalent of @mixin-content;

@define-mixin respond-to $media {
  @if $media == mobile {
    @media only screen and (max-width: $break-small) { @mixin-content; }
  } @else if $media == tablet {
    @media only screen and (min-width: $break-small-plus) { @mixin-content; }
  } @else if $media == desktop {
    @media only screen and (min-width: $break-large-plus) { @mixin-content; }
  }
}

Any help would be really appreciated!

cssmoudles and postcss-mixins does not take effect.

webpack: v1.13.2
node: v6.2.0

source code:

@define-mixin fonts $fs, $col {
    font-size: $(fs)px;
    p { color: $col; }
}
.search {
    @mixin fonts 80, blue;
}

I want to be like this:

.search {
    font-size: 80px;
}
.search p {
    color: blue;
}
// webpack.config.js
import path from 'path';
import webpack from 'webpack';
import values from 'postcss-modules-values';
import autoprefixer from 'autoprefixer';
module.exports = {
    module: {
        loaders: [
            {test: /\.css$/, loaders: ['style!css?modules&importLoaders=1&localIdentName=[local]
             -[hash:base64:6]&importLoaders=!postcss']},
        ],
    },
    postcss: [
        values,
        autoprefixer({ browsers: ['last 2 versions'] }),
        require('postcss-nested'),
        require('postcss-mixins'),
    ],

}

Conditionals inside mixins

Hi, I was wondering if I can use conditional loops inside mixins, it doesn't matter if in plain css or in js...
I am trying to do this in js, but when compiling I always get this error 'CssSyntaxError' via Webpack... if I remove the various if...else everything is fine, but this would lead to a lot of duplicated code.

Synchronous version

Is it possible to create a synchronous version for use with the require hook? Or add the appropriate option?

mixin-content

Having an issue pretty consistently where I try to use @mixin-content and can never get it to replace with what I insert into the @mixin and it leaves the @mixin-content in the resulting CSS output.

I ran gulp test on a clone of this repo and that test comes up fine.

Here is my processors order:

        var processors = [
                cssimport,
                mixins,
                simplevars,
                nested,
                extend
        ];

Sass @content feature support?

In Sass you are able to pass in arbitrary content into a mixin with the @content directive.

Is there a way to accomplish this now? Plans to support it?

$should-show: true;

@mixin some-mixin {
    @if $should-show {
        @content;
    }
}

.item {
    width: 100px;
    height: 100px;

    background: rgba(255, 0, 0, 1);

    @include some-mixin {
        background: rgba(0, 255, 0, 1);
    }
}

What about passing arguments from a mixin to a content block?

via jackmahoney's comment

@mixin foo($a, $b){
    @content($c, $d)
}

@include foo($a, $b) using($c, $d) {
    // ...
}

Nested mixin is not working

I'm creating grids with postcss-mixins like I did with sass. Here's is my mixins.

@define-mixin gColumns {
  $context: resolve(1 / $gColCount);
  @for $i from 1 to 12 {
    &--$i {
      float: left;
      width: resolve($context * $i) + '%';
    }
  }
}

@define-mixin mq $break {
  @if $break == medium {
    @media (min-width: $brkPointMd) and (max-width: $brkPointLg) {
      @mixin-content;
    }
  }
  @if $break == small {
    @media (min-width: $brkPointSm) and (max-width: $brkPointMd) {
      @mixin-content;
    }
  }
  @if $break == xs {
    @media (min-width: $brkPointXs) and (max-width: $brkPointSm) {
      @mixin-content;
    }
  }
  @if $break == large {
    @media (min-width: $brkPointLg) {
      @mixin-content;
    }
  }
}

I used that mixin in my css file.

@component grid {
  @mixin clearfix;
  @extend centered;
  @e col {
    width: 100%;
    @mixin mq small{
      @mixin gColumns;
      color: red;
    }
    @mixin mq xs{
      color: blue;
    }
    @mixin mq medium{
      color: green;
    }
    @mixin mq large{
      color: cyan;
    }
  }
}

But @mixin gColumns in @mixin mq small block is not worked as I expected. It only got @mixin gColumns in my css file and it did nothing.
Here is my css output:

.grid {
    float: none;
    display: block;
    margin-left: auto;
    margin-right: auto
}

.grid {
    zoom: 1;
}

.grid:before, .grid:after {
    content: "";
    display: table
}

.grid:after {
    clear: both
}

.grid__col {
    width: 100%
}

@media (min-width: 420px) and (max-width: 900px) {
    .grid__col {
        @mixin gColumns;
        color: red
    }
}

@media (min-width: 1px) and (max-width: 420px) {
    .grid__col {
        color: blue
    }
}

@media (min-width: 900px) and (max-width: 1350px) {
    .grid__col {
        color: green
    }
}

@media (min-width: 1350px) {
    .grid__col {

        color: cyan
    }
}

How to nest mixins?

Supposed I have a "between" mixin that takes two breakpoints defined from a map, and creates a media query from them. I know things like media-minmax and custom-media exist, but they don't do precisely what I need.

So, I have code that looks like this:

.test {
    @mixin between md, lg {
        @mixin row;
    }
}

This is output as:

@media only screen and (min-width:768px) and (max-width:991px) {
    .test {
        @mixin row
    }
}

Is there a way to have the @mixin-content that my "between" mixin spits out (@mixin row, in this scenario) actually be evaluated?

'mixinsDir' option issue

I'm building js/css bundle via webpack, with postcss-loader and postcss-mixins, writing mixins directly in js.
Everything is fine if I use this syntax, with 'mixins' option

postcss([ require('postcss-mixins')({ mixins: {} }) ])

the mixin is found and compiled to css, and if I debug the 'mixins' value I correctly get an Obj

"clearfix": {
    "mixin": {
        "background-color": "red",
        "&::after": {
            "content": "\"\"",
            "display": "table",
            "clear": "both"
        }
    }
}

Now, I want to put all my .js mixins in a separate folder, but as soon as I switch to the 'mixinsDir' option with this syntax

require('postcss-mixins')({
    mixinsDir: path.join(__dirname, 'mixins')
})

and if I debug the 'mixins' value I get this:

mixins: {
    "clearfix": {
        "clearfix": {
            "background-color": "red",
            "text-decoration": "underline",
            "&::after": {
                "content": "\"\"",
                "display": "table",
                "clear": "both"
            }
        }
    }
}

I get this error

ERROR in ./~/css-loader?sourceMap!./~/postcss-loader!./app/login/assets/main.css
Module build failed: TypeError: Cannot read property 'name' of undefined
    at insertMixin (/lessboiler2/node_modules/postcss-mixins/index.js:72:22)
    at discoverMixins (/lessboiler2/node_modules/postcss-mixins/index.js:170:17)
    at /lessboiler2/node_modules/postcss-loader/node_modules/postcss/lib/container.js:139:34
    at /lessboiler2/node_modules/postcss-import/node_modules/postcss/lib/container.js:71:26
    at Rule.each (/lessboiler2/node_modules/postcss-import/node_modules/postcss/lib/container.js:58:22)
    at Rule.walk (/lessboiler2/node_modules/postcss-import/node_modules/postcss/lib/container.js:70:21)
    at /lessboiler2/node_modules/postcss-loader/node_modules/postcss/lib/container.js:74:32
    at Root.each (/lessboiler2/node_modules/postcss-loader/node_modules/postcss/lib/container.js:58:22)
    at Root.walk (/lessboiler2/node_modules/postcss-loader/node_modules/postcss/lib/container.js:70:21)
    at Root.walkAtRules (/lessboiler2/node_modules/postcss-loader/node_modules/postcss/lib/container.js:137:25)
 @ ./app/login/assets/main.css 4:14-139 13:2-17:4 14:20-145

What am I doing wrong?

Converting SCSS mixin help

Hey there, more a question than an issue:

I'm trying to convert a scss mixin to postcss that handles :hover selectors.
Is it possible to return a nested object as a mixin or how would you handle this ?

@mixin link-colors($normal, $hover: false, $active: false, $visited: false, $focus: false) {
  color: $normal;
  @if $visited {
    &:visited {
      color: $visited;
    }
  }
  @if $focus {
    &:focus {
      color: $focus;
    }
  }
  @if $hover {
    &:hover {
      color: $hover;
    }
  }
  @if $hover == false {
    &:hover {
      color: lighten($normal, 12%);
    }
  }
  @if $active {
    &:active {
      color: $active;
    }
  }
}

Struggling to create a dynamic mixin

Hi folks,

first, thanks for the wonderful plugin and your work! i'm struggling to create a dynamic gradient mixin. My first attempt to solve a basic linear-gradient was a .pcss file like this:

@define-mixin gradientVertical $colorA, $stopA, $colorB, $stopB {
  background: -moz-linear-gradient(top, $(colorA) $(stopA), $(colorB) $(stopB)); /* FF3.6-15 */
  background: -webkit-linear-gradient(top, $(colorA) $(stopA), $(colorB) $(stopB)); /* Chrome10-25,Safari5.1-6 */
  background: linear-gradient(to bottom, $(colorA) $(stopA), $(colorB) $(stopB));
}

it's working, yay! but the downside is the explicit calling of every single variable in there.

what if i just want to add an additional color-stop? i'll have to create another mixin... this can't be the solution i thought and so i started to try it with a javascript mixin:

https://gist.github.com/rvetere/8069ef1f6836f94f79141038d8c0b7b0

this is my attempt so far - it is working! well, not completely finished yet - but the case i am testing right now will come out with the correct output of a working linear-gradient.

The problem remaining and why i want to ask here - how can we handle the case where we need to output several variants of the same property?

I'm showing this in the return of my gist - it was my obvious bad attempt to generate multiple background-image definitions for the several browser implementations.

but clearly as javascript works - i'm duplicating the key's this way in my object, actually overriding the previous value it got and so the outcoming object will only contain 1 single background-image in the end -> the last one that was defined which has won.

i can see this in my outcoming css - only one survives the game...

do you guys know any workaround in such a mixin to solve this case?

Why use @define-mixin and @mixin to replace @mixin and @include in sass?

We use @mixin to declare a mixin and @include to use. When I move node-sass to post-css, the mixin can't parse until I change @mixin to @define-mixin.

Why do that? It seem to be not convenient for me.

base.scss

.nav-activity {

    @mixin ui-icon($icon, $image) {
        .ui-icon-#{$icon} {
            background: image-url('/' + $image + '.png') no-repeat;
        }
    }
    @include ui-icon('a', 'b');
}

gulpfile.js

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


gulp.task('sass', function(){
    var processors = [
        require('postcss-mixins'),
        require('postcss-simple-vars'),
        autoprefixer({browsers: ['ChromeAndroid > 1', 'iOS >= 4', 'ie > 6', 'ff > 4']}),
        require('postcss-easings')
    ];

    gulp.src('./base.scss')
        .pipe(postcss(processors, {parser: scss}))
        .pipe(gulp.dest('./dist'));
});

Console

$ gulp sass
[17:20:24] Using gulpfile ~/tmp/postcss/gulpfile.js
[17:20:24] Starting 'sass'...
[17:20:24] Finished 'sass' after 125 ms

events.js:141
      throw er; // Unhandled 'error' event
      ^
Error: postcss-mixins: /Users/linxixuan/tmp/postcss/base.scss:30:5: Undefined mixin ui-icon
    }
    @mixin ui-icon $icon, $image {
    ^
        .ui-icon-$(icon) {

Default value syntax

The JS function mixins work great but it would be handy to allow default values when defining a mixin.

Maybe a comma separated, $var: value type syntax.

@define-mixin icon $network: twitter, $color: blue {
    .icon.is-$(network) {
        color: $color;
    }
    .icon.is-$(network):hover {
        color: white;
        background: $color;
    }
}

@mixin icon;
@mixin icon twitter blue;
@mixin icon youtube red;

@mixin-content in JS mixin functions?

Is there any way to access the @mixin-content when defining mixins as js functions? It seems the first argument include complete source of the file which uses the mixin.

Support async mixins

What do you think about supporting async mixins for mixins that return a promise? I think this would be excellent for a sprite mixin, for example, where some file I/O is required.

Make @mixin wrap parent

Is there a way to make this work? Thanks!

using ^4.0.1

Mixin:

@define-mixin mq $point, $value:null{
   @if $point == desk_large {
       @media (max-width: $desk_large) { @mixin-content; }
   }
}

postcss:

.element a{
  position: relative;
  @mixin mq desk_large{
    background: blue;
  }
}

Output is:

.element a{
  position: relative;
  @media (max-width: 1600px) {
      background: blue;
  }
}

should be:

.element a{
  position: relative;
}

@media (max-width: 1600px) {
    .element a{
      background: blue;
    }
}

Request mixinDirGlobs instead or in addition to mixinsDir

How would you feel about introducing a mixinsDirGlobs option of some kind? I'm trying to filter-out my specs, which are also in my mixins folder, where my mixin is named foo.js and its spec is named foo.spec.js.

if ( path.extname(file) === '.js' ) {

If nothing else, I'd like some way to filter-out these *.spec.js files. If it were a glob, I could do *!(.spec).js.

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.