Search code examples
cssimportsassmedia-queriesload-order

Using @use for importing media queries file SASS


When importing my .scss media queries file into my main.scss I would like the media queries to be loaded in after my initial styles to avoid errors.

The problem is that @use rules must be written before any other rules. I can include it for now by using @import at the end of the main.scss file but as @import is being deprecated, I'd like to know if there is a method of utilising @use without creating any more files.


Solution

  • If you declare your media queries as a @mixin you can @include them wherever you want:

    _media.scss

    @mixin queries {
      @media (min-width: 300px) {
        .second {
          background: green;
        }
      }
    
      @media (max-width: 600px) {
        .third {
          background: blue;
        }
      }
    }
    

    style.scss

    @use "media";
    
    .first {
      background: red;
    }
    
    @include media.queries;
    

    style.css

    After running sass style.scss style.css you'll get:

    .first {
      background: red;
    }
    
    @media (min-width: 300px) {
      .second {
        background: green;
      }
    }
    @media (max-width: 600px) {
      .third {
        background: blue;
      }
    }