Skip to content

Instantly share code, notes, and snippets.

@zvodd
Last active July 4, 2020 03:31
Show Gist options
  • Save zvodd/83a03400f0030487da40078ca353d4b6 to your computer and use it in GitHub Desktop.
Save zvodd/83a03400f0030487da40078ca353d4b6 to your computer and use it in GitHub Desktop.
Using Sass and PostCSS together in Gatsby

install packages

    npm add gatsby-plugin-sass node-sass postcss-import postcss-preset-env

gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        postCssPlugins: [
          require('postcss-import'),
          require('postcss-preset-env')({
            stage: 0
          })
        ]
      }
    },
    ...

You can then use mordern CSS features and Sass together:

custom-media.scss:

///////////////////////////////////
// Future CSS Custom Media Queries (PostCSS)
///////////////////////////////////
@custom-media --media-min-small (min-width: 450px);

///////////////////////////////////
// SASS mixin
///////////////////////////////////
@mixin media-max-small {
  @media (max-width: 449px) {
    @content;
  }
}

typography.module.scss:

@import '../styles/custom-media.scss';

:root {
  --base-unit: 17;

  --font-base-size: calc(var(--base-unit) / 16 * 100%);
  --font-base-line-height: calc(22 / var(--base-unit));
  --font-large-size: calc(19 / var(--base-unit) * 1rem);
  --font-large-line-height: calc(24 / 19);

  --font-family-body-text: "Montserrat", -apple-system, sans-serif;
}

.paragraph {
  font-family: var(--font-family-body-text);
  font-size: var(--font-base-size);
  line-height: var(--font-base-line-height);
  margin: 0.5rem 0 1rem 0;

  ///////////////////////////////////
  // SASS Mixin
  ///////////////////////////////////
  @include media-min-small {
    font-size: var(--font-base-size);
    line-height: var(--font-base-line-height);
  }

  ///////////////////////////////////
  // Future CSS Custom Media Queries (PostCSS)
  ///////////////////////////////////
  @media (--media-min-medium) {
    font-size: var(--font-large-size);
    line-height: var(--font-large-line-height);
  }
}

someotherstyle.scss:

.title {
  ///////////////////////////////////
  // CSS Modules (PostCSS)
  ///////////////////////////////////
  composes: responsiveTitle1 from './typography.module.scss';
  font-family: var(--font-family-heading);
  
  ///////////////////////////////////
  // Future CSS nesting (PostCSS)
  ///////////////////////////////////
  @nest & a{
    color:blue;
  }

  ///////////////////////////////////
  // Sass nesting
  ///////////////////////////////////
  a{
    color:blue;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment