Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Sass @import and Partials

Sass @import

Sass helps us reduce repetitive CSS code and save development time.

We can create separate code files based on different concerns, such as files for variable definitions, color-related files, and font-related files.


Sass Import Files

Similar to CSS, Sass supports the @import directive.

The @import directive lets us import other files and their contents.

The CSS @import directive creates an extra HTTP request each time it is called. However, the Sass @import directive includes the file within the CSS, requiring no extra HTTP request.

The Sass @import directive syntax is as follows:

@import filename;

**Note:** You do not need to specify a file extension when including a file; Sass will automatically add the .scss extension.

In addition, you can also import CSS files.

After importing, we can use the imported file's variables in the main file.

In the following example, import 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 in the standard.scss file to import the reset.scss file:

standard.scss file code:

@import

"reset"

;

body

{

 

font-family

:

Helvetica

,

sans-serif

;

 

font-size

:

18px

;

 

color

:

red

;

}

Convert the above code into CSS code as shown below:

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 file name. This tells Sass not to compile it into a CSS file.

However, we do not 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:

$myPink

:

#EE82EE

;

$myBlue

:

#4169E1

;

$myGreen

:

#8FBC8F

;

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 files with the same name but with and without an underscore in the same directory; for example, _colors.scss and colors.scss cannot exist in the same directory at the same time, otherwise the underscore-prefixed file will be ignored.