8 Tips to Help You Get the Best out of Sass

Share this article

Sass creates Syntactically Awesome Style sheets, or at least thats what it is supposed to do.

When used effectively, Sass helps to build scalable and DRY CSS. When used incorrectly however, Sass can actually increase file size and add unnecessary or duplicate code.

Below is a series of hints and tips to help you get the best out of Sass…

1. Structure Your Sass

Getting your site structure correct from the beginning is vital for any new Sass project. Using partials allows you to break the CSS up into smaller more manageable blocks of code that are easier to maintain and develop.

Partial files are created using an underscore and are not output as separate CSS files. Each partial should be imported using a master Sass file (global.scss) in the root of the Sass folder.

For example, here’s a sample folder structure to demonstrate this:

vendor/
base/
|
|-- _variables.scss
|-- _mixins.scss
|-- _placeholders.scss

framework/
modules/
global.scss

This folder structure ensures the site is easy to work with, and add to. For example, new modules can easily be added to the module folder and then added to global.scss using @import.

To demonstrate, here’s a sample global.scss file:

/* VENDOR - Default fall-backs and external files.
========================================================================== */

@import 'vendor/_normalize.scss';


/* BASE - Base Variable file along with starting point Mixins and Placeholders.
========================================================================== */

@import 'base/_variables.scss';
@import 'base/_mixins.scss';
@import 'base/_placeholders.scss';


/* FRAMEWORK - Structure and layout files.
========================================================================== */

@import 'framework/_grid.scss';
@import 'framework/_breakpoints.scss';
@import 'framework/_layout.scss';


/* MODULES - Re-usable site elements.
========================================================================== */ 

@import 'modules/_buttons.scss';
@import 'modules/_lists.scss';
@import 'modules/_tabs.scss';

And as a side point, you might want to check out Hugo’s extensive post on Sass architecture for more tips in this area.

2. Use Sass Variables More Effectively

Variables are one of the more straightforward features of Sass but are still on occasion used incorrectly. Creating a site-wide naming convention is essential when working with Variables. Without one, they become harder to understand and re-use.

Here are some tips for creating useful variables:

  • Don’t be to vague when naming your Variables.
  • Have and stick to a naming convention (Modular, BEM, etc.)
  • Ensure the variable use is justified.

Here are some good examples:

$orange: #ffa600; 
$grey: #f3f3f3; 
$blue: #82d2e5;

$link-primary: $orange;
$link-secondary: $blue;
$link-tertiary: $grey;

$radius-button: 5px;
$radius-tab: 5px;

And some bad examples:

$link: #ffa600;
$listStyle: none;
$radius: 5px;

3. Reduce Mixin Usage

A mixin is a great way to include sections of code multiple times within a site. However, including a mixin is the same as copying and pasting the styles throughout the CSS file. It creates a mass of duplicate code and can bloat your CSS file.

A mixin therefore should only be used if an argument is present, to quickly create modified styles.

Here’s an example:

@mixin rounded-corner($arc) {
    -moz-border-radius: $arc;
    -webkit-border-radius: $arc;
    border-radius: $arc;  
}

This rounded-corner mixin can be used in any situation simply by changing the value of $arc, making it a worthwhile mixin:

.tab-button {
     @include rounded-corner(5px); 
}

.cta-button {
     @include rounded-corner(8px); 
}

A bad example might look like this:

@mixin cta-button {
    padding: 10px;
    color: #fff;
    background-color: red;
    font-size: 14px;
    width: 150px;
    margin: 5px 0;
    text-align: center;
    display: block;
}

This mixin has no argument and would therefore be better written as a placeholder, which brings us to point 4.

4. Embrace Placeholders

Unlike mixins, placeholders can be used multiple times without adding any duplicate code. This makes them a much friendlier option for outputting DRY CSS:

%bg-image {
    width: 100%;
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
}

.image-one {
    @extend %bg-image;
    background-image:url(/img/image-one.jpg");
}

.image-two {
    @extend %bg-image;
    background-image:url(/img/image-two.jpg");
}

And the compiled CSS:

.image-one, .image-two {
    width: 100%;
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
}

.image-one {
    background-image:url(/img/image-one.jpg") ;
}

.image-two {
    background-image:url(/img/image-two.jpg") ;
}

The repeated code in the placeholder is output only once with only the unique styles being applied to the individual selectors. If unused, the placeholder styles are not output at all.

Tying in with point 3, placeholders can be used alongside mixins to reduce duplicate code and still keep the flexibility of a mixin…

/* PLACEHOLDER 
============================================= */

%btn {
    padding: 10px;
    color:#fff;
    curser: pointer;
    border: none;
    shadow: none;
    font-size: 14px;
    width: 150px;
    margin: 5px 0;
    text-align: center;
    display: block;
}

/* BUTTON MIXIN 
============================================= */

@mixin  btn-background($btn-background) {
    @extend %btn;
    background-color: $btn-background;
    &:hover {
        background-color: lighten($btn-background,10%);
    }
}

/* BUTTONS
============================================= */

.cta-btn {
    @include btn-background(green);
}

.main-btn {
    @include btn-background(orange);
}

.info-btn {
    @include btn-background(blue);
}

5. Use Functions for Calculations

Functions are used to perform calculations. A Sass function does not output any CSS. Instead, it returns a value that can be used in the CSS. This is useful for calculations that will be made throughout the site.

For example, functions are useful for calculating the percentage width of a given element:

@function calculate-width ($col-span) {
    @return 100% / $col-span 
}

.span-two {
    width: calculate-width(2); // spans 2 columns, width = 50%
}

.span-three {
    width: calculate-width(3); // spans 3 columns, width = 33.3%
}

6. Order Your Work

Place all mixins, functions, placeholders and variables in their relevant partial file. Keeping blocks of code together will ensure they are easy to edit and reuse in the future.

Site-wide elements should be kept together in a base folder. The base folder should contain global variables such as fonts and colour schemes:

$font-primary: 'Roboto', sans-serif; 
$font-secondary: Arial, Helvetica, sans-serif;

$color-primary: $orange;
$color-secondary: $blue;
$color-tertiary: $grey;

Module-specific mixins, functions, and variables should be kept within the correct module’s partial file:

$tab-radius: 5px;
$tab-color: $grey;

7. Limit Nesting

Overusing nested rules in Sass can cause a lot of issues, from complex code to over-specificity and too much reliance on the HTML structure of a page. These things can cause issues further down the line and potentially increase the need for the inclusion of !important, which should generally be avoided.

Here are some golden rules for nesting:

  • Never go more then 3 levels deep.
  • Ensure the CSS output is clean and reusable.
  • Use nesting when it makes sense to, not as a default option.

8. Keep Things Simple

The concluding point I’ll make in this post is to keep things as simple as possible. The purpose of Sass is to write cleaner more manageable CSS. Before creating any new mixins, variables, or functions, ensure that their presence will enhance development and not overcomplicate things. All Sass features are useful when used in the correct situations and in moderation.

Creating an endless list of variables without clear usage, or a complex function that is difficult to understand for anyone other than the author is not the intention and will not aid development or produce DRY CSS.

Conclusion

That’s it for this list of Sass tips. You might not agree with all of these. Sass is still a fairly new technology so we’re continuing to learn new best practices with it. If you have your own suggestions, feel free to offer a comment.

Frequently Asked Questions (FAQs) about SASS Best Practices

What are the key benefits of using SASS in web development?

SASS, or Syntactically Awesome Style Sheets, is a CSS preprocessor that helps make coding more efficient and manageable. It offers several benefits such as nested syntax, variable declaration, mixins, and functions. These features allow developers to write cleaner, more reusable code. SASS also supports inheritance, which can reduce the amount of CSS you need to write, making your stylesheets smaller and faster to load.

How can I effectively use variables in SASS?

Variables in SASS are a powerful feature that can help you maintain consistency in your design. You can define a variable once, such as a color or font, and then reuse it throughout your stylesheet. This makes it easier to make changes to your design, as you only need to update the variable value in one place.

What are mixins and how can they be used in SASS?

Mixins in SASS are a way to define styles that can be reused throughout your stylesheet. They can take arguments, which makes them incredibly flexible. For example, you could create a mixin for a button style, and then reuse it for all your buttons, passing in different colors or sizes as arguments.

How can I use nesting in SASS to make my code more readable?

Nesting in SASS allows you to nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. Be careful not to over-nest though, as it can make your stylesheets harder to read and maintain.

What are the best practices for organizing my SASS files?

It’s a good practice to split your SASS code into separate files, or partials, and then import them into a single file. This can make your code easier to maintain and understand. You might separate your variables, mixins, base styles, layout styles, and module styles into their own files.

How can I use SASS functions to make my code more efficient?

SASS functions allow you to define complex operations that you can reuse throughout your stylesheet. For example, you could create a function to calculate the color contrast between two colors, and then use it to ensure your text is always readable against its background color.

What are the best practices for using SASS in a team environment?

When working in a team, it’s important to establish and follow coding conventions. This might include naming conventions for variables and mixins, commenting guidelines, and rules for how to structure and organize your SASS files.

How can I use SASS to create responsive designs?

SASS can be a powerful tool for creating responsive designs. You can use variables and mixins to define styles for different screen sizes, and then use media queries to apply these styles. This can make your code more reusable and easier to maintain.

How can I optimize my SASS for performance?

There are several ways to optimize your SASS for performance. This might include avoiding deep nesting, keeping your selectors as simple as possible, and minimizing the use of expensive CSS properties. You should also consider using a tool to minify your compiled CSS.

How can I debug my SASS code?

SASS provides several features to help you debug your code. This includes the @debug rule, which prints the value of a variable or expression to the console, and the @warn rule, which prints a warning message to the console. You can also use source maps to map your compiled CSS back to your original SASS code.

Cathy DuttonCathy Dutton
View Author

I am a front-end developer working with Sass, HTML, and JavaScript. I have over 8 years professional experience and am passionate about responsive development, modular coding, and object oriented CSS.

LouisLsasssass architecturesass mixins
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week