12Importing

When you’re developing, it’s often useful to have many smaller style sheets rather than one huge one. This can be a pain for web performance. If you have five style sheets on a particular page, it can make the page loading times much slower because each style sheet needs a separate request to load.

Importing is a process by which a lot of files are turned into a few files. Sass has a neat little trick whereby the smaller style sheets are imported into the larger one as it is compiled into CSS. All you need to type is @import, followed by the name of the Sass file you want to import. You can mix Original Sass and SCSS at will with imports—it’s all the same. Just say @import “sub_page”; and you’re done!

If you don’t want a Sass file to generate a corresponding CSS file, just start the filename with an underscore (if you’re familiar with Rails, this is a bit like doing a Rails partial). For example, you can name the file _sub_page.sass. In the import line, you can leave off the underscore. If you don’t mind that a separate style sheet is created for the child page, it can just be named sub_page.sass.

It’s as simple as that. Any variables or mixins (we’ll get to those later) you used in the imported style sheet can be used in the parent file too.

What To Do...
  • Create a separate file.
    basics/_colors.scss
     
    $​main_color​: #336699;
     
     
    // ​A​ ​LOT​ ​MORE​ ​COLORS​ ​GO​ ​HERE​.
    basics/widths.scss
     
    $​main_width​: 720px;
     
     
    // ​A​ ​LOT​ ​MORE​ ​WIDTHS​ ​GO​ ​HERE​.
  • Import into the main file.
     
    @import​ ​"colors"​;
     
    @import​ ​"widths"​;

    (We don’t need to include the underscore or extension with _colors.scss.)

    basics/bundling_example.scss
     
    @import​ ​"colors"​;
     
    @import​ ​"widths"​;
     
     
    #page {
     
    color: $main_color;
     
    width: $main_width; }
     
     
    #sidebar {
     
    color: darken($main_color, 10%);
     
    width: $main_width*0.2; }

    This compiles to:

     
    #page {
     
    color: #336699;
     
    width: 720px; }
     
     
    #sidebar {
     
    color: #264c73;
     
    width: 144px; }

    Remember the rule about the underscores—when we compile into CSS, the two imported files will not be treated the same. The widths.scss file will create its own separate CSS file because it doesn’t start with an underscore.

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset