Search code examples
sasspostcss

PostCSS and breakpoint Mixins


recently i switched from SASS to PostCSS. However still cant figure out how to make breakpoint mixin with map-get (i insalled map-get plugin).

So this is SCSS version

@mixin bp-max($bp) {
  @media (max-width: map-get($bps, $bp)) {
    @content;
  }
}

$bps: (
  "mob": 480px,
  "tab": 768px,
  "desk": 1200px,
  "deskBig": 1600px,
) !default;

But as i can see map-get is not the same as for sass.


Solution

  • I am in the same switching process as you are, from scss to postcss, mainly to use also tailwindcss.

    Anyway I found the solution to use similar mixins in postcss as those you mention in scss.

    However you need to install several postcss plugins for that to work:

    • postcss-nested
    • postcss-simple-vars
    • postcss-mixins
    • postcss-map-get

    That should allow you to use a similar approach, however the syntax changes significantly:

    This is how your mixins will look like with postcss and these plugins (no 'quotes' in the breakpoint names, no parenthesis in the mixin definitions ...):

    $breakpoints-up: (
      small: 440px,
      medium: 640px,
      large: 1024px,
      xlarge: 1400px,
    );
    $breakpoints-down: (
      xsmall: 439px,
      small: 639px,
      medium: 1023px,
      large: 1399px,
    );
    /* xsmall < 440 < small < 640 < medium < 1024 < large < 1400 < xlarge */
    
    @define-mixin breakpoint-up $size {
      @media (min-width: map-get($breakpoints-up, $size)) {
        @mixin-content;
      }
    }
    
    @define-mixin breakpoint-down $size {
      @media (max-width: map-get($breakpoints-down, $size)) {
        @mixin-content;
      }
    }
    

    And when you want to use the breakpoints instead of @include, you need to use @mixin, like this:

    body {
      background-color: white;
      @mixin breakpoint-down medium {
        background-color: black;
      }
    }