Categories
Web development

Sass @import and Partials

For sure you’ve noticed already that Sass makes CSS fun again. Today we’ll go a bit further with Sass Rules and we’ll go through the @import rule and Sass Partials.

I play with code.

Sass keeps the CSS code DRY (Don’t Repeat Yourself). One way to write DRY code is to keep related code in separate files.

You can create small files with CSS snippets to include in other Sass files. Examples of such files can be: reset file, variables, colors, fonts, font-sizes, etc. 

Sass Importing Files

Just like CSS, Sass also supports the @import directive.

Sass Import Syntax:

@import filename;

You can import as many files as you need in the main file:

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

Example:

Let’s look at an example: You’ll need to create a reset file called “reset.scss”, that looks like this:

SCSS Syntax (reset.scss):

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

and now we want to import the “reset.scss” file into another file which I called “test.scss”.

Here is how we do it: It is normal to add the @import directive at the top of a file; this way its content will have a global scope:

SCSS Syntax (test.scss):

@import "reset";

body {
  font-family: Helvetica, sans-serif;
  font-size: 20px;
  color: green;
}

Output:

Sass Partials

By default, Sass transpiles all the .scss files directly. However, when you want to import a file, you do not need the file to be transpiled directly.

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

So, a partial Sass file is 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 transpiled directly to “colors.css”):

Example:

“_colors.scss”:

$myRed: #DF361C;
$myBrown: #5B1D13;
$myBlue: #32C6D7;

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

@import "colors";

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

Enjoy coding!

Read also:

CSS Blurred Background Image

CSS Gradient Border