Sass @import
Sass can help us reduce repetitive CSS code and save development time.
We can create code files based on different properties, such as files for variable definitions, color-related files, font-related files, etc.
Sass Import Files
Similar to CSS, Sass supports@importdirective.
The @import directive allows us to import other files and content.
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, requiring no additional HTTP request.
The Sass @import directive syntax is as follows:
@import filename;
Note:You don't need to specify the file extension when including files; Sass will automatically add the .scss extension.
Additionally, you can also import CSS files.
After importing, we can use variables and other content from the imported files in the main file.
The following example imports the variables.scss, colors.scss, and reset.scss files.
Sass code:
@import "colors";
@import "reset";
Next, let's create a reset.scss file:
reset.scss file code:
body,
ul,
ol {
margin: 0;
padding: 0;
}
Then, we use the @import directive in the standard.scss file to import the reset.scss file:
standard.scss file code:
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
Converting the above code to CSS code is shown below:
CSS code:
margin: 0;
padding: 0;
}
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
Sass Partials
If you don't 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, we don't need to add the underscore in the import statement.
Sass Partials syntax format:
_filename;
The following example creates a _colors.scss file, but it will not be compiled into a _colors.css file:
_colors.scss file code:
$myBlue: #4169E1;
$myGreen: #8FA6BC;
If you want to import this file, you don't need to use the underscore:
Example
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: $myBlue;
}
Note:Please do not place files with the same name, one with an underscore and one without, in the same directory. For example, _colors.scss and colors.scss cannot coexist in the same directory; otherwise, the file with the underscore will be ignored.
Other Extensions