Using Mixins, Includes and Imports in SCSS / SASS

Published on

I recently posted an article on compiling SCSS/SASS files in Visual Studio which turned out to be very popular indeed.

I mentioned mixins and imports but didn't explain them in any real depth. So, here's my chance to furnish you with some of the ways we can reuse code in SCSS & SASS.

How to use SCSS Imports

SCSS imports improve over standard CSS imports by combining multiple stylesheets during compilation, instead of importing the additional files when the page loads.

By combining multiple stylesheets together at compile time, we can reduce the number of HTTP requests that the client needs to make when they load your page. Giving obvious speed and load-time improvements to your site.

Simply add the imports to the top of the file using @import:

// style.scss 

// importing single file from the partial folder
@import 'partial/_menu';

// importing multiple files from the same directory
@import 'article', 'product';

Note that you can import multiple files on a single line, instead of each import requiring it's own individual @import like in standard CSS.

Also notice that you don't need to specify the full filename when importing, you can reference 'partial/_menu' instead of 'partial/_menu.scss'.

How to use SCSS Mixins & Includes

Mixins are sets of rules defined within your Scss files, that allow you to define styles that can be re-used throughout the stylesheet.

We then reference the mixin rules at a later date by using @include:

@mixin reset-list {
  padding: 2px;
  list-style: none;
}

@mixin horizontal-list {
  @include reset-list;

  li {
    display: inline-block;
    margin: {
      left: 5px;
      right: 5em;
    }
  }
}

nav ul {
  @include horizontal-list;
}

As per the above example. we create two rules called reset-list & horizontal-list. The horizontal-list rule includes the reset-list rule, so we just need to include horizontal-list to get both.

These kinds of nested mixins allow you to create complex rules for your Scss stylesheets, without the need to re-write lots of code.


Article Categories: # scss # saas # css # visual-studio
Date Published: Apr 4, 2020

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Teambuilding & fitness

Our friends at Company Fitness League are building fun platform for getting fit with your colleagues!