Curriculum
Course: Sass Tutorial
Login
Text lesson

Sass @import and Partials

You have the option to generate concise CSS snippet files to incorporate into other Sass files. Examples of such files include resets, variables, color schemes, font definitions, and font size configurations.

Sass Importing Files

Similar to CSS, Sass also incorporates the @import directive, enabling the inclusion of content from one file into another.

While the CSS @import directive poses a significant drawback in terms of performance, as it triggers an additional HTTP request each time it’s invoked, Sass’s @import directive seamlessly integrates the file’s content into the CSS, eliminating the need for extra HTTP calls during runtime.

Sass Import Syntax:

@import filename;

Tip: File extensions (.sass or .scss) are not required to be specified when using the @import directive in Sass, as Sass automatically assumes them. Additionally, Sass allows for the import of CSS files. After importing, any variables or mixins defined in the imported file can be utilized in the main file.

You can import multiple files as needed in the main file.

Example 

@import “variables”;
@import “colors”;
@import “reset”;

Consider an example where we possess a reset file labeled “reset.scss,” which is structured as follows:

Example 

SCSS Syntax (reset.scss):

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

Now, suppose we aim to import the “reset.scss” file into another file named “standard.scss”.

The process involves placing the @import directive typically at the beginning of a file, ensuring that its content obtains a global scope.

SCSS Syntax (standard.scss):

@import “reset”;

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

Thus, upon transpilation of the “standard.scss” file, the resulting CSS will resemble the following:

CSS output:

Example 

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

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

Sass Partials

By default, Sass directly transpiles all .scss files. However, when importing a file, direct transpilation is unnecessary.

Sass offers a solution: if a filename begins with an underscore, Sass skips transpilation. Such files are referred to as partials in Sass.

Thus, a partial Sass file is denoted by a leading underscore in its filename.

Sass Partial Syntax:

_filename;

The subsequent example depicts a partial Sass file named “_colors.scss”. (This file will not undergo direct transpilation into “colors.css”):

Example 

“_colors.scss”:

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

When importing the partial file, you can exclude the underscore. Sass intelligently recognizes that it should import the “_colors.scss” file:

Example 

@import “colors”;

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