Sass @import
Sass can help us reduce repetitive CSS code and save development time.
We can install different properties to create some code files, such as files for variable definitions, color-related files, font-related files, etc.
Sass Import Files
Similar to CSS, Sass supports the @import
directive.
The @import directive allows us to import other files, etc.
The CSS @import directive creates an additional HTTP request each time it is called. However, the Sass @import directive includes the file in the CSS, eliminating the need for an extra HTTP request.
The syntax for the Sass @import directive is as follows:
@import filename;
Note: When including a file, you do not need to specify the file extension; Sass will automatically add the .scss extension.
Additionally, you can also import CSS files.
After importing, we can use variables from the imported files in the main file.
The following example imports the variables.scss, colors.scss, and reset.scss files.
Sass Code:
@import "variables";
@import "colors";
@import "reset";
Next, we create a reset.scss file:
reset.scss File Code:
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
Then, we use the @import directive to import the reset.scss file in the standard.scss file:
standard.scss File Code:
@import "reset";
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
Converting the above code to CSS code, it looks like this:
CSS Code:
html, body, ul, ol {
margin: 0;
padding: 0;
}
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
Sass Partials
If you do not want a Sass code file to be compiled into a CSS file, you can add an underscore at the beginning of the filename. This tells Sass not to compile it into a CSS file.
However, you do not need to add the underscore in the import statement.
The syntax for Sass Partials is:
_filename;
The following example creates a _colors.scss file, but it will not be compiled into a _colors.css file:
_colors.scss File Code:
$myPink: #EE82EE;
$myBlue: #4169E1;
$myGreen: #8FBC8F;
If you want to import this file, you do not need to use the underscore:
Example
@import "colors";
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: $myBlue;
}
Note: Do not place underscore and non-underscore versions of the same filename in the same directory, such as _colors.scss and colors.scss, as the underscore file will be ignored.