SCSS @import explained
SCSS @import Detailed Explanation
In SCSS, the @import directive is used to import external style sheets. Unlike regular CSS’s @import directive, SCSS’s @import directive merges imported stylesheets into a single file when compiled into CSS, rather than loading them separately. This reduces HTTP requests and improves website performance.
How to Use
In SCSS, using the @import directive to import external stylesheets is straightforward. Simply use the @import directive wherever you need to import the style sheet. The syntax is as follows:
@import 'path/to/your/stylesheet';
Example
Suppose there are the following SCSS files:
variables.scss
$primary-color: #3498db;
$secondary-color: #2ecc71;
mixins.scss
@mixin button-styles {
background-color: <span class="katex math inline">primary-color;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
@mixin link-styles {
color:</span>primary-color;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
main.scss
@import 'variables';
@import 'mixins';
.button {
@include button-styles;
}
.link {
@include link-styles;
}
In main.scss, we use the @import directive to import variables.scss and mixins.scss, respectively, and then apply the variables defined in variables and the mixins defined in mixins.
Running Results
After compiling the above code into CSS, the contents of main.css are as follows:
$primary-color: #3498db;
$secondary-color: #2ecc71;
@mixin button-styles {
background-color: $primary-color;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
@mixin link-styles {
color: $primary-color;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.button {
background-color: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
.link {
color: #3498db;
text-decoration: none;
}
.link:hover {
text-decoration: underline;
}
As you can see, main.css includes the variables and mixins defined in variables.scss and mixins.scss, as well as the content in main.scss that applies these styles.
Summary
The @import directive allows you to easily import external stylesheets into SCSS and use the variables and mixins defined in those stylesheets, providing great convenience and flexibility. In actual development, you can split your stylesheets into multiple files and organize them by functionality or module to make your code easier to maintain and manage. Furthermore, using the @import directive can reduce HTTP requests during page load, improving website performance.