Optimization with SASS

The problem with using CSS is that it can become repetitive when used in large projects. Like using same values of margins, paddings, radius. SASS provides a way to store these values in ONE variable and to use that variable instead.

SASS provides various concepts that optimize CSS. Like discussed above using variables for all the color names and fonts will remove the repetition. A piece of code from Open-Event-Webapp is shown below for declaring variable names.

//config.scss

@charset "UTF-8";
 
// Colors
$black: #000;
$white: #fff;
$red: #e2061c;
$gray-light: #c9c8c8;
$gray: #838282;
$gray-dark: #777;
$gray-extra-dark: #757575;
$gray-extra-light:#e7e7e7 !default;
$gray-perfect :#ddd;
$blue: #253652;
$orange: #e12b00;
$vivid-blue: #2196F3;
$pure-orange: #ff8700;
$light-purple: #ebccd1;
$red-dark: #e52d27;
$light-black: #333333;
$light-skyblue : #b7cdff !default;
$gray-trackshade: #999;
$blue-shade: #2482d3;
$dark-black: rgba(22, 22, 22, 0.99) !default;
$black-main:#232323 !default;
$timeroom-color:rgba(0,0,0,.10) !default;
$session-color: $gray-trackshade !default;
$header-color: #f8f8f8 !default;
$main-background: #fff !default;

// Corp-Colors
$corp-color: $white !default;
$corp-color-dark: darken($corp-color, 15%) !default;
$corp-color-second: $red !default;
$corp-color-second-dark: darken($corp-color-second, 15%) !default;

Nesting

SASS supports nesting concept. The nested SCSS changes to CSS when compiled. A good approach follows nesting elements to three-degree maximum.

// Nesting in application.scss session-list (Open-Event-Webapp)

.session{

  &-list {

    li{
     cursor: pointer;
      }
   .label {
     background: #ff8700;
     border-color: $light-purple;
     color: #FFFFFF;
     font-weight: 500;
     font-size: 80%;
     margin-left: -8px;
    }
   .session-title {
      margin-top: 0.1em;
       .session-link {
         font-size: 12px;
        }
    }
 }
 &-location{
 text-align: left;
 }

}

The output generated after compilation will be

//Code from schedule.css in Open-event-webapp

.session-list li {
 cursor: pointer; 
}

.session-list .label {
 background: #ff8700;
 border-color: #ebccd1;
 color: #FFFFFF;
 font-weight: 500;
 font-size: 80%;
 margin-left: -8px; 
}

.session-list .session-title {
 margin-top: 0.1em; 
}

 .session-list .session-title .session-link {
 font-size: 12px;
 }

.session-location {
 text-align: left; 
}

Mixins

Mixins are another way to optimize the SASS code. Mixins are just like functions that let us pass the values as parameters to make the code more flexible.

// Simple mixin for button
@mixin btn($color, $width, $height) {
 display: block;
 font: 16px “Open sans”, arial;
 color: $color;
 width: $width;
 height: $height;
}

Using these type of simple approaches make CSS more effective and efficient. It will enhance the workflow and help us to write cleaner code.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.