Sass @import en Partials

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

One way to write DRY code is to store 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; so there is no need for additional HTTP calls 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 to import files, 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:

Voorbeeld

@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 are going 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 content will 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 look like this:

CSS output:

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

Sass Partials (local files)

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

Sass heeft een mechanisme: als je een bestandnaam begint met een onderstrepingsteken, zal Sass het niet vertalen. Bestanden die op deze manier worden genoemd, worden in Sass partials genoemd.

Daarom wordt de naam van de partial Sass bestanden voorafgegaan door een onderstrepingsteken:

Sass Partial Syntax:

_filename;

Het volgende voorbeeld toont de partial Sass bestand genaamd "_colors.scss". (Dit bestand wordt niet direct geconverteerd naar "colors.css"):

Voorbeeld

"_colors.scss":

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

Nu, als je deze partial bestand importeert, laat dan de onderstreping weg. Sass begrijpt dat het bestand "_colors.scss" moet worden geïmporteerd:

Voorbeeld

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