Sass @import und Partials
- Vorherige Seite Sass-Nesting
- Nächste Seite Sass @mixin
Sass can keep CSS code dry (DRYDon't Repeat Yourself, don't 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
Instructions.
@import
Instructions allow you to include the content of one file in another file.
Due to performance issues, CSS @import
Instructions have a major drawback; an additional HTTP request is created every time it is called. However, Sass @import
Instructions include files in CSS; so 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
Instruction 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:
Beispiel
@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
Instructions; so its 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 hat ein Mechanismus: Wenn Sie den Dateinamen mit einem Unterstrich beginnen, übersetzt Sass es nicht. Dateien, die auf diese Weise benannt sind, werden in Sass als Partials bezeichnet.
Daher werden Partial-Sass-Dateien mit führendem Unterstrich benannt:
Sass Partial-Syntax:
_Dateiname;
Das folgende Beispiel zeigt die Partial-Sass-Datei mit dem Namen "_colors.scss". (Diese Datei wird nicht direkt in "colors.css" konvertiert):
Beispiel
"_colors.scss":
$myPink: #EE82EE; $myBlue: #4169E1; $myGreen: #8FBC8F;
Jetzt, wenn Sie diese Partial-Datei importieren, lassen Sie die Unterstriche aus. Sass versteht es, dass es die Datei "_colors.scss" importieren soll:
Beispiel
@import "colors"; body { font-family: Helvetica, sans-serif; font-size: 18px; color: $myBlue; }
- Vorherige Seite Sass-Nesting
- Nächste Seite Sass @mixin