Sass @import and Partials

Sass can keep CSS code dry (DRYDon't Repeat Yourself, don't repeat yourself).

One way to write DRY code is to save related code in separate files.

You can use CSS snippets to create small files and include them in other Sass files. For example, such files can be: reset files, variables, colors, fonts, etc.

Sass File Imports

Like CSS, Sass also supports @import Directives.

@import Directives allow you to include the content of one file in another file.

Due to performance issues, CSS @import Directives have a major drawback; an additional HTTP request is created every time it is called. However, Sass @import Directives include files in CSS; therefore, no additional HTTP calls are needed at runtime!

Sass Import Syntax:

@import filename;

Tip:You do not need to specify the file extension; Sass will automatically assume you are referring to a .sass or .scss file. You can also import CSS files.@import Directives import files, and then you can use any variables or mixins defined in the imported files in the main file.

You can import any number of files in the main file:

Example

@import "variables";
@import "colors";
@import "reset";

Let's look at an example: suppose we have a reset file named "reset.scss" that looks like this:

SCSS Syntax (reset.scss):

html,
body,
ul,
ol {
  margin: 0;
  padding: 0;
}

Now we want to import the "reset.scss" file into another file named "standard.scss".

This is what we do: generally, we add it at the top of the file. @import Directives; this makes its content have a global scope:

SCSS Syntax (standard.scss):

@import "reset";
body {
  font-family: Helvetica, sans-serif;
  font-size: 18px;
  color: red;
}

Therefore, when the "standard.css" file is translated, the CSS will be as follows:

CSS Output:

html, body, ul, ol {
  margin: 0;
  padding: 0;
}
body {
  font-family: Helvetica, sans-serif;
  font-size: 18px;
  color: red;
}

Sass Partials (partial files)

By default, Sass directly translates all .scss files. However, when importing files, you do not need the files to be directly translated.

Sass has a mechanism: if you start the filename with an underscore, Sass will not transpile it. Files named in this way are called partials in Sass.

Therefore, partial Sass files are named with a leading underscore:

Sass Partial Syntax:

_filename;

The following example shows a partial Sass file named "_colors.scss". (This file will not be directly converted to "colors.css"):

Example

"_colors.scss":

$myPink: #EE82EE;
$myBlue: #4169E1;
$myGreen: #8FBC8F;

Now, if you import this partial file, omit the underscore. Sass understands that it should import the file "_colors.scss":

Example

@import "colors";
body {
  font-family: Helvetica, sans-serif;
  font-size: 18px;
  color: $myBlue;
}